Nothing Special   »   [go: up one dir, main page]

Bioinformants - Client.Gui Java - Io.Bufferedreader Java - Io.Inputstreamreader Java - Io.Outputstreamwriter Java - Io.Printwriter

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

/*

* InterBio.java
* -- RELEASE: beta 1.00
* (C)2004 Davila, Jacinto - Vivas, Almathely.
*
* LICENSE
* =======
* This program 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 any later version.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
* More details at http://nux.ula.ve
*
* CHANGES
* =======
*
* Applet interface for Bioinformants. This applet creates the GUI to
* interact with the Bioinformant-server. It allows a user to prepare a
* text to be sent to an agent or an application running on the server
* on his/her behalf. It delivers this text, normally a command, but also
* input data to applications running on a pseudo-term on the side of
* the server. Finally, it catches any output from the applications and
* returns it to the user wrapped in html.
*
* As for version alfa 0.60, a new modality is introduced. The user in
front of
* the browser can send message to other users on other sessions. This
* program will deliver messages among users to the WebApp, where these
* messages will be distributed among their destinations. This will
* be the ChatRoom extension of Bioinformants. (Notice that these messages
* are delivered in full length to BioTerminal, which identifies their
* destination.
*
* We want to thank an anonymous programmer for the ideas applied to
* BioTalk and related classes.
*
* Created on October 13, 2002, 10:46 AM
* Modified on June 26, 2003. 10:00 PM
* Last modified on November 19, 2004. 10:00 AM
*
* @version bioinformantes beta 1.00
*/

package bioinformants.client.gui;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;

import javax.swing.*;

public class InterBio extends JApplet {

/** Initializes the applet InterBio */


public void init() {
ChatLdr = new BioTalkRespLdr();
//ChatConj = new BioTalkConjugate();
BioTalkConjugate.init();
initComponents();
//ContextualHTML.add(getActionByName(DefaultEditorKit.cutAction));
//Para el chat log
FullChatLogPane = new javax.swing.JScrollPane();
ChatLog = new javax.swing.JTextArea();
FullChatLogPane.setBackground(new java.awt.Color(204, 204, 204));
FullChatLogPane.setViewportView(ChatLog);
//Fin de lo del chat log
PseudoOutput.setCaretColor(new java.awt.Color(255, 255, 0));
PseudoOutput.setText(prompt);
texto = prompt;
resourceDir = this.getCodeBase().toString();
time = new Timer(this);
time.setChatRoomURL(resourceDir);
time.setPseudoTermURL(resourceDir);
time.start();
System.out.println("InterBio: Constructor applet...
"+resourceDir+servletTerminal);
Input.setText("");
sendMessage("", resourceDir + servletTerminal, null);
}

/** This method is called from within the init() method to


* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
ContextualHTML = new javax.swing.JPopupMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
ContextualInput = new javax.swing.JPopupMenu();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
PanelBase = new javax.swing.JPanel();
Tabs = new javax.swing.JTabbedPane();
PseudoOutputPane = new javax.swing.JScrollPane();
PseudoOutput = new javax.swing.JTextArea();
FullOutputPane = new javax.swing.JScrollPane();
FullOutput = new javax.swing.JTextArea();
InputScrollPane = new javax.swing.JScrollPane();
Input = new javax.swing.JTextArea();
PanelSalida = new javax.swing.JPanel();
ChatOutputPane = new javax.swing.JScrollPane();
ChatOutput = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
PanelBotones = new javax.swing.JPanel();
Botones = new javax.swing.JScrollPane();
jPanel2 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
OverButton = new javax.swing.JButton();
OverButton1 = new javax.swing.JButton();
PanelComandos = new javax.swing.JPanel();
Comandos = new javax.swing.JScrollPane();
FlowComandos = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();

ContextualHTML.setName("copyPaste");
ContextualHTML.setInvoker(FullOutput);
jMenuItem1.setText("Copiar");
jMenuItem1.setName("copy");
jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem1MouseClicked(evt);
}
});

ContextualHTML.add(jMenuItem1);

jMenuItem2.setText("Pegar");
jMenuItem2.setName("paste");
jMenuItem2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem2MouseClicked(evt);
}
});

ContextualHTML.add(jMenuItem2);

jMenuItem3.setText("Cortar");
jMenuItem3.setName("cut");
jMenuItem3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem3MouseClicked(evt);
}
});

ContextualHTML.add(jMenuItem3);

ContextualInput.setName("copyPaste");
ContextualInput.setInvoker(Input);
jMenuItem4.setLabel("Copiar");
jMenuItem4.setName("copy");
jMenuItem4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem4MouseClicked(evt);
}
});

ContextualInput.add(jMenuItem4);

jMenuItem5.setLabel("Pegar");
jMenuItem5.setName("paste");
jMenuItem5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem5MouseClicked(evt);
}
});
ContextualInput.add(jMenuItem5);

jMenuItem6.setLabel("Cortar");
jMenuItem6.setName("cut");
jMenuItem6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenuItem6MouseClicked(evt);
}
});

ContextualInput.add(jMenuItem6);

PanelBase.setLayout(new java.awt.BorderLayout());

PanelBase.setMinimumSize(new java.awt.Dimension(400, 800));


PanelBase.setPreferredSize(new java.awt.Dimension(400, 800));
Tabs.setFont(new java.awt.Font("Arial", 0, 12));
Tabs.setMinimumSize(new java.awt.Dimension(405, 400));
Tabs.setPreferredSize(new java.awt.Dimension(405, 800));
Tabs.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
TabsMouseClicked(evt);
}
});

PseudoOutputPane.setBackground(new java.awt.Color(0, 0, 0));


PseudoOutputPane.setForeground(new java.awt.Color(255, 255, 255));
PseudoOutput.setFont(new java.awt.Font("Arial", 0, 12));
PseudoOutput.setBackground(new java.awt.Color(0, 0, 0));
PseudoOutput.setForeground(new java.awt.Color(255, 255, 255));
PseudoOutput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
PseudoOutputKeyPressed(evt);
}
});

PseudoOutputPane.setViewportView(PseudoOutput);

Tabs.addTab("Shell", PseudoOutputPane);

FullOutput.setBackground(new java.awt.Color(204, 204, 204));


FullOutput.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
FullOutputMouseClicked(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
FullOutputMouseReleased(evt);
}
});

FullOutputPane.setViewportView(FullOutput);

Tabs.addTab("HTML", FullOutputPane);

Input.setBackground(new java.awt.Color(204, 204, 204));


Input.setMinimumSize(new java.awt.Dimension(70, 400));
Input.setPreferredSize(new java.awt.Dimension(70, 80));
Input.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
InputMouseClicked(evt);
}
});

InputScrollPane.setViewportView(Input);

Tabs.addTab("Input Text", InputScrollPane);

PanelBase.add(Tabs, java.awt.BorderLayout.CENTER);

PanelSalida.setLayout(new java.awt.BorderLayout());

PanelSalida.setPreferredSize(new java.awt.Dimension(117, 90));


ChatOutputPane.setPreferredSize(new java.awt.Dimension(50, 100));
ChatOutput.setBackground(new java.awt.Color(204, 204, 204));
ChatOutputPane.setViewportView(ChatOutput);

PanelSalida.add(ChatOutputPane, java.awt.BorderLayout.CENTER);

jLabel1.setFont(new java.awt.Font("Arial", 1, 12));


jLabel1.setText("Salida del ChatRoom, del Agente y del Biotalk");
PanelSalida.add(jLabel1, java.awt.BorderLayout.NORTH);

PanelBase.add(PanelSalida, java.awt.BorderLayout.NORTH);

PanelBotones.setLayout(new java.awt.BorderLayout());

Botones.setName("botones");
jPanel2.setPreferredSize(new java.awt.Dimension(100, 20));
jPanel2.setAutoscrolls(true);
jButton1.setText("Ver LogChat");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});

jPanel2.add(jButton1);

jButton2.setText("BioTutor");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton2MousePressed(evt);
}
});

jPanel2.add(jButton2);

Botones.setViewportView(jPanel2);

PanelBotones.add(Botones, java.awt.BorderLayout.CENTER);

OverButton.setBackground(new java.awt.Color(51, 51, 51));


OverButton.setFont(new java.awt.Font("Arial", 0, 12));
OverButton.setForeground(new java.awt.Color(204, 204, 204));
OverButton.setText("Enviar");
OverButton.setBorder(new
javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
OverButton.setPreferredSize(new java.awt.Dimension(41, 25));
OverButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OverButtonActionPerformed(evt);
}
});

PanelBotones.add(OverButton, java.awt.BorderLayout.NORTH);

OverButton1.setBackground(new java.awt.Color(51, 51, 51));


OverButton1.setFont(new java.awt.Font("Arial", 0, 12));
OverButton1.setForeground(new java.awt.Color(204, 204, 204));
OverButton1.setText("Enviar");
OverButton1.setBorder(new
javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
OverButton1.setPreferredSize(new java.awt.Dimension(41, 25));
OverButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OverButton1ActionPerformed(evt);
}
});

PanelBotones.add(OverButton1, java.awt.BorderLayout.SOUTH);

PanelBase.add(PanelBotones, java.awt.BorderLayout.EAST);

PanelComandos.setLayout(new java.awt.BorderLayout());

PanelComandos.setPreferredSize(new java.awt.Dimension(240, 85));


Comandos.setPreferredSize(new java.awt.Dimension(2, 70));
FlowComandos.setToolTipText("Comandos");
Comandos.setViewportView(FlowComandos);

PanelComandos.add(Comandos, java.awt.BorderLayout.SOUTH);

jLabel2.setFont(new java.awt.Font("Arial", 1, 12));


jLabel2.setText("Almacenamiento de Comandos de usuario");
PanelComandos.add(jLabel2, java.awt.BorderLayout.CENTER);
jLabel2.getAccessibleContext().setAccessibleName("");

PanelBase.add(PanelComandos, java.awt.BorderLayout.SOUTH);

getContentPane().add(PanelBase, java.awt.BorderLayout.CENTER);

}//GEN-END:initComponents

private void PseudoOutputKeyPressed(java.awt.event.KeyEvent evt)


{//GEN-FIRST:event_PseudoOutputKeyPressed
if (evt.getKeyCode() == evt.VK_ENTER) {
String content = PseudoOutput.getText();

int pos = content.lastIndexOf(prompt);

String command = content.substring(pos +


prompt.length(),content.length());
if(!mantener(command))
parseSentence(command);
// entrega el comando
// restaura el prompt
PseudoOutput.append(" \n" + prompt);
texto = PseudoOutput.getText();
// Coloca el cursor de texto justo despues del prompt
/*try {
thisCaret.setDot(textArea.getDocument().getLength()+1);
} catch (java.lang.IllegalArgumentException e) {
displayArea.append("ERROR:"+e.getMessage()
+""+e.toString());
} finally {*/

PseudoOutput.setCaretPosition(PseudoOutput.getDocument().getLength());
//}
/*
* try { CommandParser parser = new CommandParser( new
* BufferedReader(new StringReader(command))); String[] args =
* parser.parse(); displayArea.setText(""); for (int i = 0; i <
* args.length; i++) { displayArea.append(args[i]); } } catch
* (Exception ioe) { displayArea.setText("ERROR:" +
* ioe.getMessage() + ":" + ioe.getCause() + "\n"); }
*/
}else{
if (evt.getKeyCode() == evt.VK_BACK_SPACE) {
String ultimo = texto.substring(texto.length()-
1,texto.length());
System.out.println("Texto..."+texto+" Ultimo.."+ultimo);
if(ultimo.compareTo(">")==0){
System.out.println("Entre...");
PseudoOutput.setText(texto);
String ultimo2 = texto.substring(texto.length()-
2,texto.length());
System.out.println(ultimo2);
if(ultimo2.compareTo(">>")!= 0){
PseudoOutput.append(">");
texto = PseudoOutput.getText();
}
//PseudoOutput.append(">");
}
//Para que no se pueda borrar lo anterior... pero no s�
como evitarlo...
evt.consume();
texto = PseudoOutput.getText();
System.out.println("Texto acutalizado... "+texto);
}
else{
texto = PseudoOutput.getText();
System.out.println("Texto acutalizado... "+texto);
}
}
}//GEN-LAST:event_PseudoOutputKeyPressed

private void FullOutputMouseReleased(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_FullOutputMouseReleased
System.out.println("Texto seleccionado:
"+FullOutput.getSelectedText());
}//GEN-LAST:event_FullOutputMouseReleased

private void jMenuItem6MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jMenuItem6MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.cut();*/
Input.cut();
}//GEN-LAST:event_jMenuItem6MouseClicked
private void jMenuItem5MouseClicked(java.awt.event.MouseEvent evt)
{//GEN-FIRST:event_jMenuItem5MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.paste();*/
Input.paste();
}//GEN-LAST:event_jMenuItem5MouseClicked

private void jMenuItem4MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jMenuItem4MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.copy();*/
Input.copy();
}//GEN-LAST:event_jMenuItem4MouseClicked

private void InputMouseClicked(java.awt.event.MouseEvent evt) {//GEN-


FIRST:event_InputMouseClicked
if(evt.getButton()== 3)
ContextualInput.show(Input,evt.getX(), evt.getY());
}//GEN-LAST:event_InputMouseClicked

private void OverButton1ActionPerformed(java.awt.event.ActionEvent evt)


{//GEN-FIRST:event_OverButton1ActionPerformed
// Add your handling code here:
// Encodes the data..
// data = URLEncoder.encode("texto = " + jTextArea4.getText() + "",
"UTF-8");
lastMessage = message; // Store the previous message, if any.
message = Input.getText(); // Get the message from the interface
// Send it over..
Input.setText(""); // Cleans the area..

println("Ud: " + message);


parseSentence(message); // Parsing and analyzing before delivering.

//sendMessage(message, resourceDir + servletTerminal, null);


}//GEN-LAST:event_OverButton1ActionPerformed

private void FullOutputMouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_FullOutputMouseClicked
if(evt.getButton()== 3)
ContextualHTML.show(FullOutput,evt.getX(), evt.getY());
}//GEN-LAST:event_FullOutputMouseClicked

private void jMenuItem3MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jMenuItem3MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.cut();*/
FullOutput.cut();
}//GEN-LAST:event_jMenuItem3MouseClicked

private void jMenuItem2MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jMenuItem2MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.paste();*/
FullOutput.paste();
}//GEN-LAST:event_jMenuItem2MouseClicked

private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jMenuItem1MouseClicked
/*JTextArea temp = (JTextArea)
((JPopupMenu)evt.getComponent()).getInvoker();
temp.copy();*/
FullOutput.copy();
}//GEN-LAST:event_jMenuItem1MouseClicked

private void jButton1MouseClicked(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jButton1MouseClicked
if(!ver){
setTabSelected(4);
JButton boton = (JButton)evt.getComponent();
boton.setText("Cerrar ChatLog");
Tabs.addTab("ChatLog", FullChatLogPane);
ver = true;
System.out.println("El valor de ver es "+ver);
}
else{
JButton boton = (JButton)evt.getComponent();
boton.setText("Ver ChatLog");
ChatLog.setText("");
ver = false;
Tabs.remove(FullChatLogPane);
}
}//GEN-LAST:event_jButton1MouseClicked

private void jButton2MousePressed(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jButton2MousePressed
Input.setText("Biotutor, ");
}//GEN-LAST:event_jButton2MousePressed

private void jButton1MousePressed(java.awt.event.MouseEvent evt)


{//GEN-FIRST:event_jButton1MousePressed
/*if(!ver){
setTabSelected(4);
JButton boton = (JButton)evt.getComponent();
boton.setText("Cerrar ChatLog");
Tabs.addTab("ChatLog", FullChatLogPane);
ver = false;
System.out.println("El valor de ver es "+ver);
}
else{
JButton boton = (JButton)evt.getComponent();
boton.setText("Ver ChatLog");
ChatLog.setText("");
ver = true;
Tabs.remove(FullChatLogPane);
}*/
}//GEN-LAST:event_jButton1MousePressed

private void TabsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-


FIRST:event_TabsMouseClicked
int i = Tabs.getSelectedIndex();
setTabSelected(i);
switch(i){
case 0:
System.out.println("Pseudoterminal");
break;
case 1:
System.out.println("HTML");
break;
case 2:
System.out.println("Input");
break;
}
}//GEN-LAST:event_TabsMouseClicked

private void OverButtonActionPerformed(java.awt.event.ActionEvent evt)


{//GEN-FIRST:event_OverButtonActionPerformed
// Add your handling code here:
// Encodes the data..
// data = URLEncoder.encode("texto = " + jTextArea4.getText() + "",
"UTF-8");
lastMessage = message; // Store the previous message, if any.
message = Input.getText(); // Get the message from the interface
// Send it over..
Input.setText(""); // Cleans the area..

println("Ud: " + message);


parseSentence(message); // Parsing and analyzing before delivering.

//sendMessage(message, resourceDir + servletTerminal, null);


}//GEN-LAST:event_OverButtonActionPerformed

public void sendMessage(String m, String destination, String f) {


String text = m;
// This is the code going to the servlet
try {
System.out.println("/"+destination+"/");
theConnection = (HttpURLConnection)(new
URL(destination)).openConnection();
//System.out.println("Interbio: lo hizo..");
theConnection.setRequestMethod("POST");
//System.out.println("Interbio: lo hizo tambien...");
} catch (Exception e) {
System.out.println("Interbio: Couldn't open connection to" + "
send file " + e.toString());
e.printStackTrace();
};
try {
// Set the parameters.
theConnection.setDoInput(true);
theConnection.setDoOutput(true);
theConnection.setAllowUserInteraction(true);
theConnection.setUseCaches(false);
// Recovers the file.
// text = FileInput.getText();
String l = "" + text.length() + "";
//System.out.println("Longitud " + text.length());

// Set the headers


theConnection.setRequestProperty("Content-Length", l);
theConnection.setRequestProperty("Content-Type", "text/html");

if (f!=null) {
theConnection.setRequestProperty("bioinformants.datafilename", f );
};

or = new OutputStreamWriter(theConnection.getOutputStream());
or.write(text);
showStatus("Sending a message.. "); // To the Applet
or.flush();
or.close();
// Trace
//System.out.println("message: " + text + " sent");
// Open an input stream to receive the response.
//System.out.println("Aqui es el problema, al pedir el
getInputStream" + theConnection.toString());
try{
ir = new InputStreamReader(theConnection.getInputStream());
in = new BufferedReader(ir);
}
catch(Exception e){
System.out.println("InterBio: Error al leer el InputSream
"+e.getMessage()+ " "+in);
e.printStackTrace();
}
//System.out.println("Interbio: Capte el inputStream 1");
// Mark the current position in the input stream.
// in.mark(10);
// Receive the response...
//System.out.println("Interbio: Voy a leer...");
receiveAnswer(in);
//System.out.println("Interbio: Lei");
in.close();
} catch (Exception e){
System.out.println("Interbio: Coudn't connect -- "+
e.toString());
//e.printStackTrace();
};
}

/** receiveAnswer, retrieves the output from the servlet */


public void receiveAnswer(BufferedReader in) {
showStatus("Receiving from the server.. ");
readStream(in);
}

/** readStream, a generic method to read a stream */


private void readStream(BufferedReader r) {
String recibido = "";
try {
//System.out.println("Leyendo desde el proceso");
int c;
// r.reset(); // put the reader at the previous mark if any
// if (!(r.ready())) { println(" Nup!.. couldn't read ");
return; }
//else { println("YES!"); }
// while(r.ready()) {
// System.out.println("Buffer ready");
while((c = r.read()) != -1) {
// c = r.read();
recibido = recibido + (char)c ;
System.out.print((char)c);
}
// r.mark(10); // Mark the current position without lookahead.
// println(recibido);
parseAnswer(recibido);

// System.out.print("Mensaje recibido<" + recibido + "|");


// String b = " " ;
// while((b = r.readLine())!= null) {
// System.out.println("Recibido " + b) ;
// }
// wait(); // wait for the stream to have data..
} catch (Exception e) {
println("Stream can't be read:" + e); }
// return recibido;
}

/** println, to print a text (with carriage return)


* on the Salida pane of the GUI */
public void println(String m) {
String p = FullOutput.getText();
if(m.length()>0)
FullOutput.setText( p + m + "\n");
}

public void printlnPseudo(String m) {


if(m.length()>0){
String p = filtrar(m);
//String p = PseudoOutput.getText();
//String temp = p + m;
//System.out.println("// "+p+m+" //");
// st = new StringTokenizer(temp,"\n");
//while (st.hasMoreTokens()) {
// a = st.nextToken();
//System.out.println("//"+a+"//");
//b = a.substring(i,i+1);
//while(b.equals(" ")){
// i++;
// b = a.substring(i,i+1);
//}
//PseudoOutput.setText(temp);
PseudoOutput.append(p);
PseudoOutput.append(" \n" + prompt);

PseudoOutput.setCaretPosition(PseudoOutput.getDocument().getLength());
texto = PseudoOutput.getText();
}
}

public void printlnChat(String m) {


/*String p = ChatOutput.getText();
String temp = p + m;
System.out.println("//"+p+m+"//");*/
if(m.length()>0){
// st = new StringTokenizer(temp,"\n");
//while (st.hasMoreTokens()) {
// a = st.nextToken();
// System.out.println("//"+a+"//");
//b = a.substring(i,i+1);
//while(b.equals(" ")){
// i++;
// b = a.substring(i,i+1);
//}
ChatOutput.append(m);
//ChatOutput.setText(temp);
}
}

public void printChatLog(String m) {


ChatLog.setText(m);
}

public void whoIsThere(Vector users) {


for(int i=0;i<usersChat.size();i++){
JButton boton = (JButton)usersChat.elementAt(i);
jPanel2.remove(boton);
}
usersChat.removeAllElements();
if(users.size()>0){
for(int k=0;k<users.size();k++){
String user = (String)users.elementAt(k);
JButton boton = new JButton();
boton.setText(user);
boton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt)
{
botonMousePressed(evt);
}
});
jPanel2.add(boton);
usersChat.add(boton);
}
}
}

private void botonMousePressed(java.awt.event.MouseEvent evt) {


JButton boton = (JButton)evt.getComponent();
System.out.println("InterBio: el text del boton /"+boton.getText()
+"/");
Input.setText(boton.getText()+", ");
evt.consume();
}

/** println, to print a text (withOUT carriage return)


* on the Salida pane of the GUI */
public void print(String m) {
String p = FullOutput.getText();
FullOutput.setText(p + m);
}

/** parseSentence(String to be parsed)


* Methods to parse an string with the mensaje from the user and
* deliver a co-relate or answer, either to the servlet or back to the
* user.
*
* Observe that this method and its associates parse the text, try to
* identify its content and decide what to do with it.
*
* If the string _s is a command or
* cannot be identified, it is passed to the
* BioTerminal on the server.
*
* If the string is a query that can be answered locally, this is
done.
*
*
*/
public void parseSentence(String s_) {
int idx=0, idxSpace=0;
int _length=0; // actual no of elements in set
int _maxLength=200; // capacity of set
int _w;

// s_=s_.toLowerCase()+" ";
s_ = s_ + " ";

//System.out.println("Starting to parse sentence " + s_);

// Check for tildes and clean them


while(s_.indexOf("'")>=0)
s_=s_.substring(0,s_.indexOf("'"))+s_.substring(s_.indexOf("'")
+1,s_.length());

// It assumes the token is of unknown type


int _type = BioTalk.UNKNOWN ;

// it seeks for a type id


typed: for(int i=0;i<ChatLdr.cq.length && _type==BioTalk.UNKNOWN;i+
+) {
// System.out.println("Comparing with " + i );
_type=ChatLdr.cq[i].identify(s_);

if (_type!=BioTalk.UNKNOWN) {
break typed;
};
};

//System.out.println("The type of the sentence " + s_ + " is " +


_type);

// it decides what to do
if(_type == BioTalk.COMMAND ) {
parseCommand(s_);
} else {
if(_type == BioTalk.QUERY) {
parseQuery(s_);
} else {
//
_resp=ChatLdr.cq[i].converse(s_.substring(idx,s_.length()));
//String mes = mantener(s_);
sendMessage(s_, resourceDir + servletTerminal, null);
}
};

// A loop to parse the string starting with the fist token


/* bigloop: for(_length=0; _length<_maxLength && idx <
s_.length(); _length++){
// find end of the first token
idxSpace=s_.indexOf(" ",idx);
if(idxSpace == -1) idxSpace=s_.length();

// translate the token into a response


String _resp=null;

// It assume the token is of unknown type


int _type = BioTalk.UNKNOWN ;
for(int i=0;i<BioTalk.num_chats && _resp == null;i++) {

_type=ChatLdr.cq[i].identify(s_.substring(idx,s_.length()));
System.out.println("The type of the sentence is " + _type);
// if the first token something..
if(_type == BioTalk.COMMAND ) {
parseCommand(s_.substring(idx,s_.length()));
} else {
if(_type == BioTalk.QUERY) {
parseQuery(s_.substring(idx,s_.length()));
} else {
//
_resp=ChatLdr.cq[i].converse(s_.substring(idx,s_.length()));
sendMessage(s_, resourceDir + servletTerminal,
null);
}
}
break bigloop;

}
// eat blanks
while(s_.length() > ++idxSpace &&
Character.isWhitespace(s_.charAt(idxSpace)));
idx=idxSpace;

// this means that no key could be identified.


/** if(idx >= s_.length()) {
* _resp=ChatLdr.cq[BioTalk.num_chats-
1].converse(s_.substring(idx,s_.length()));
* System.out.println("InterBio: I couldn't identify this" +
_resp);
* // println(_resp);
* sendMessage(s_, resourceDir + servletTerminal, null);
* } */
}

/** parseCommand(String to be parsed)


* A method to parse a command and to
* deliver a co-relate to the servlet or back to the user.
*/
public void parseCommand(String s_) {
int idx=0, idxSpace=0;
int _length=0; // actual no of elements in set
int _maxLength=200; // capacity of set
int _w;

//System.out.println("Starting to parse command " + s_);

// Check for tildes


while(s_.indexOf("'")>=0)
s_=s_.substring(0,s_.indexOf("'"))+s_.substring(s_.indexOf("'")
+1,s_.length());

// Check whether the command contains the key 'entrada', which


denotes a link to the input panel
idxSpace = s_.indexOf("entrada");
if(idxSpace > -1) {
//String inputText = FileInput.getText();
String inputText = "";
sendMessage(inputText, resourceDir + servletTerminal, null);
// Notifies the user
println("InterBio: The text in the entrada panel has been
sent.");
} else {
message = s_;
// Notifies the user
println("InterBio: command '" + message + "', sent.");
sendMessage(message, resourceDir + servletTerminal, null);
}

/** parseQuery(String to be parsed)


* this method parses a query and gets an anwers LOCALLY */
public void parseQuery(String s_) {
int idx=0, idxSpace=0;
int _length=0; // actual no of elements in set
int _maxLength=200; // capacity of set
int _w;

//System.out.println("Starting to parse query " + s_);

s_=s_.toLowerCase()+" ";
while(s_.indexOf("'")>=0)
s_=s_.substring(0,s_.indexOf("'"))+s_.substring(s_.indexOf("'")
+1,
s_.length());

bigloop: for(_length=0; _length<_maxLength && idx < s_.length();


_length++){
// find end of the first token
idxSpace=s_.indexOf(" ",idx);
if(idxSpace == -1) idxSpace=s_.length();

String _resp=null;
for(int i=0;i<BioTalk.num_chats && _resp == null;i++) {

_resp=ChatLdr.cq[i].converse(s_.substring(idx,s_.length()));
if(_resp != null) {
println("InterBio: "+_resp);
break bigloop;
}
}
// eat blanks
while(s_.length() > ++idxSpace &&
Character.isWhitespace(s_.charAt(idxSpace)));
idx=idxSpace;

if(idx >= s_.length()) {


// _resp=ChatLdr.cq[BioTalk.num_chats-1].converse(s_);
_resp = "to your question `" + s_+ "', I don't know the
answer";
println("InterBio: "+ _resp);
}
}
}

/** parseAnswer retrieves the answer from the servlet and decides
* what to do with it. This can be either 1) to display the info on the
* output pane of the applet, 2) to show a html document with the
browser or
* 3) to play an audioClip. These actions are methods available to the
* applet.
*/
public void parseAnswer(String s_) {
int idx=0, idxSpace=0;
String action ;

//System.out.println("InterBio: parsing this answer " + s_);

try {
//** Check for actions
while(s_.indexOf("</ACTION>")>=0) {
action = s_.substring(s_.indexOf("<ACTION>")+8,
s_.indexOf("</ACTION>"));
s_=s_.substring(0,s_.indexOf("<ACTION>"))
+s_.substring(s_.indexOf("</ACTION>")+9,s_.length());

if ( action.indexOf("showDocument:") >= 0) {
getAppletContext().showDocument(new
URL(action.substring(action.indexOf("showDocument:")+13, action.length())),
"_blank");
};

if ( action.indexOf("play:") >= 0) {
// I may need to load the clip first
play(new URL(action.substring(action.indexOf("play:")
+1, action.length())));
};

if ( action.indexOf("showStatus:") >= 0) {

showStatus(action.substring(action.indexOf("showStatus:")+12,
action.length()));
};

println(s_); // Send the rest to the Salida Pane of the applet


} catch (Exception e) {
println("InterBio: I could not perform a command from the
server " + e);
};

public String getAppletInfo() {


return "Author: Jacinto Davila <jacinto@ula.ve>, Version: 1.0, ULA,
Venezuela, 2004";
}

public String getResourceDir() {


return resourceDir;
}

public String getServletTerminal() {


return servletTerminal;
}

public int getTabSelected() {


return tabSelected;
}

public synchronized void setTabSelected(int i) {


tabSelected = i;
}

public void destroy(){


/*try{
time.wait();
}
catch(InterruptedException e){
System.out.println("InterBio: Problemas para parar el hilo");
}*/
sendMessage("@FinSession@", resourceDir + servletTerminal, null);
}

public boolean mantener(String comando){


int keep,forget = -1;
keep = comando.indexOf("keep");
System.out.println("mantener: "+keep);
forget = comando.indexOf("forget");
System.out.println("mantener: "+forget);
FlowComandos.setToolTipText("Algo hace...");
if(keep >= 0){
JButton comandBoton = new JButton();
comandBoton.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mousePressed(java.awt.event.MouseEvent evt) {
comandBotonMousePressed(evt);
}
});
String message = quitaBlanco(comando.substring(4));
comandBoton.setText(message);
comandBoton.setVisible(true);
FlowComandos.add(comandBoton);
Comandos.setViewportView(FlowComandos);
// repaint();
return true;
}
else{
if(forget >= 0){
String message = quitaBlanco(comando.substring(7));
int cont = FlowComandos.getComponentCount();
for(int i=0;i<cont;i++){
JButton comandBoton =
(JButton)FlowComandos.getComponent(i);
System.out.println(comandBoton.getText());
System.out.println("/"+message+"/");
if(comandBoton.getText().compareTo(message)==0){
System.out.println("Lo consiguio...");
FlowComandos.remove(i);
i = cont +1;
Comandos.setViewportView(FlowComandos);
//repaint();
}
}
return true;
}
else
return false;
}
//return comando;
}

private void comandBotonMousePressed(java.awt.event.MouseEvent evt) {


JButton boton = (JButton)evt.getComponent();
System.out.println("InterBio: el text del boton /"+boton.getText()
+"/");
PseudoOutput.append(boton.getText());
evt.consume();
}

public static String quitaBlanco(String b) {


// eat blanks
int idx, idxSpace;
idx = b.length();
idxSpace = 0;
while(b.length() > ++idxSpace &&
(Character.isWhitespace(b.charAt(idxSpace))));
return b.substring(idxSpace);
}

public String filtrar(String m){


String nueva = "";
for(int i=0;i<m.length();i++){
int c = (int)m.charAt(i);
if((c >= 32 && c<=126)||(c==130)||(c==156)||(c>=160 &&
c<=165)||(c==168)||(c>=173 && c<=175)||(c==221)||(c==240)||(c==246)||
(c==221)||((char)c=='\t')||((char)c=='\n')){
nueva = nueva + (char)c;
}
}
return nueva;
}
/*public void stop(){
try{
time.wait();
}
catch(InterruptedException e){
System.out.println("InterBio: Problemas para parar el hilo");
}
}

public void start(){


this.notify();
}*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane Botones;
private javax.swing.JTextArea ChatOutput;
private javax.swing.JScrollPane ChatOutputPane;
private javax.swing.JScrollPane Comandos;
private javax.swing.JPopupMenu ContextualHTML;
private javax.swing.JPopupMenu ContextualInput;
private javax.swing.JPanel FlowComandos;
private javax.swing.JTextArea FullOutput;
private javax.swing.JScrollPane FullOutputPane;
private javax.swing.JTextArea Input;
private javax.swing.JScrollPane InputScrollPane;
private javax.swing.JButton OverButton;
private javax.swing.JButton OverButton1;
private javax.swing.JPanel PanelBase;
private javax.swing.JPanel PanelBotones;
private javax.swing.JPanel PanelComandos;
private javax.swing.JPanel PanelSalida;
private javax.swing.JTextArea PseudoOutput;
private javax.swing.JScrollPane PseudoOutputPane;
private javax.swing.JTabbedPane Tabs;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JPanel jPanel2;
// End of variables declaration//GEN-END:variables

/** Bioinformant's interface global variables */


private HttpURLConnection theConnection = null;
private String aBuffer = " ";
private InputStreamReader ir;
private BufferedReader in;
private OutputStreamWriter or;
private PrintWriter op;
private String resourceDir = "";
private String servletTerminal =
"servlet/bioinformants.server.BioTerminal";
private String servletMessenger =
"servlet/bioinformants.server.BioMessenger";
private String servletSave =
"servlet/bioinformants.server.BioSaveFile";
private int tabSelected = 0;

/** BioTalk variables */


BioTalk cq[];
BioTalkRespLdr ChatLdr;
Timer time;
// static BioTalkConjugate ChatConj;
boolean _started=false;
private String _s;
private String message; // Message to be sent to the servlet
private String lastMessage; // Last message sent
private Vector usersChat = new Vector();
private Vector usersC = new Vector();
private boolean ver = false;
private javax.swing.JScrollPane FullChatLogPane;
private javax.swing.JTextArea ChatLog;
//private javax.swing.JButton comandBoton;
private String prompt = "Shell>";
private String texto;
}

You might also like