Download Código fuente. Contador de Tiempo Invertido (por los

Document related concepts
no text concepts found
Transcript
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
//Archivo Main.java
package contador;
/**
*
* @author Alberto
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
}
//Archivo GUI.java
package contador;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
1
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
/**
*
* @author Alberto
*/
public class GUI extends javax.swing.JFrame {
/** Creates new form GUI */
public GUI() {
initComponents();
this.jTable1.setVisible(false);
Controlador c = new Controlador(this);
this.jButton1.addActionListener(c);
this.repEnum = 0;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
2
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Seleccionar archivo:");
jTextField1.setEditable(false);
jButton1.setText("Examinar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTable1.setModel(new contador.Tabla());
jTable1.setCellSelectionEnabled(true);
jTable1.setEnabled(false);
jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
escribir(evt);
}
3
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
});
jScrollPane2.setViewportView(jTable1);
jTable1.setColumnSelectionAllowed(true);
jLabel2.setText("Tiempo total en minutos:");
jTextField2.setEditable(false);
jTextField2.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextField2.setText("0");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 753, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 753, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 753, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
4
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 109,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
5
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void escribir(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
protected javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
protected javax.swing.JTable jTable1;
protected javax.swing.JTextArea jTextArea1;
6
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
protected javax.swing.JTextField jTextField1;
protected javax.swing.JTextField jTextField2;
// End of variables declaration
/**
* Variables que declaró el programador.
*/
protected JFileChooser fc;
protected JTable tt;
private int repEnum;
/**
* Métodos declarados por el programador
*/
protected void reportar(String cad, boolean t) {
if (t) {
repEnum += 1;
jTextArea1.append("-------------Reporte #" + repEnum + "-------------\n" + cad + "\n");
} else {
jTextArea1.append(cad + "\n");
}
jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
}
protected void ajustarColumnas() {
DefaultTableCellRenderer[] rend = {new DefaultTableCellRenderer(), new
DefaultTableCellRenderer()};
rend[0].setHorizontalAlignment(SwingConstants.CENTER);
7
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
rend[1].setHorizontalAlignment(SwingConstants.RIGHT);
//
TableColumn col = new TableColumn();
col = this.jTable1.getColumn("Curso");
col.setMaxWidth(90);
col.setMinWidth(90);
col.setCellRenderer(rend[0]);
col = this.jTable1.getColumn("Número");
col.setMaxWidth(65);
col.setMinWidth(65);
col.setCellRenderer(rend[0]);
col = this.jTable1.getColumn("Nombre del docente/usuario");
col.setMaxWidth(460);
col.setMinWidth(360);
col = this.jTable1.getColumn("Minutos");
col.setMaxWidth(150);
col.setMinWidth(100);
col.setCellRenderer(rend[1]);
}
protected void detallarTabla() {
this.jTable1.getTableHeader().setReorderingAllowed(false);
this.jTable1.setVisible(true);
this.jTable1.setEnabled(true);
}
}
8
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
//Archivo Controlador.java
package contador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
/**
*
* @author Alberto
*/
public class Controlador implements ActionListener {
GUI gui;
protected String ruta;
protected String[] nombre;
protected int repEnum;
protected Contador tiempos;
Controlador(GUI g) {
this.gui = g;
this.ruta = null;
this.nombre = null;
this.repEnum = 0;
this.tiempos = new Contador();
}
public void actionPerformed(ActionEvent e) {
//String ruta = "";
Object obj = e.getSource();
9
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
if (obj == this.gui.jButton1) {
String tipo = null;
if (this.gui.fc == null) {
this.gui.fc = new JFileChooser();
}
if (this.gui.fc.showOpenDialog(this.gui.getContentPane()) == JFileChooser.APPROVE_OPTION) {
this.ruta = this.gui.fc.getSelectedFile().toString();
this.gui.jTextField1.setText(ruta);
this.nombre = this.ruta.split("\\u005C");
String ext[] = this.nombre[this.nombre.length - 1].split("\\u002E");
tipo = ext[ext.length - 1];
tipo = tipo.toUpperCase();
//reportamos el nombre del archivo seleccionado
this.gui.reportar("Archivo seleccionado: " + this.nombre[this.nombre.length - 1], true);
if (tipo.equals("XLS")) {
this.gui.reportar("Archivo de Excel válido.", false);
if (!Archivo.validaArchivo(ruta)) {
this.gui.reportar("Procesamiento del archivo iniciado. Espere un momento.", false);
try {
// inicio del proceso
long ini = System.currentTimeMillis();
this.gui.tt = this.tiempos.calcTiempos(ruta);
long tot = System.currentTimeMillis() - ini;
// fin del proceso
this.gui.jTable1.setModel(this.gui.tt.getModel());
10
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
this.gui.reportar("Se procesaron" + this.tiempos.numReg + " registros en " + tot + " milisegundos.",
false);
this.gui.ajustarColumnas();
this.gui.detallarTabla();
this.gui.jTextField2.setText(this.tiempos.getTiempoTotal().toString());
} catch (Exception e2) {
this.gui.reportar("Ocurrió un error al calcular los tiempos.", false);
}
} else {
this.gui.reportar("Error. Archivo INVÁLIDO.", false);
}
} else {
this.gui.reportar("No se seleccionó un archivo de Excel válido.", true);
}
} else {
this.gui.reportar("No se selccionó el archivo.", true);
}
}
}
}
//Archivo Acceso.java
package contador;
import java.util.Date;
import java.util.LinkedList;
/**
11
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
*
* @author Alberto
*/
public class Acceso {
private LinkedList<Date> accesos;
private Integer tiempo;
public Acceso(){
this.accesos = new LinkedList<Date>();
this.tiempo = new Integer(0);
}
/**
* @return the accesos
*/
public LinkedList<Date> getAccesos() {
return accesos;
}
/**
* @param accesos the accesos to set
*/
public void setAccesos(LinkedList<Date> accesos) {
this.accesos = accesos;
}
/**
* @return the tiempo
*/
12
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
public Integer getTiempo() {
return tiempo;
}
/**
* @param tiempo the tiempo to set
*/
public void setTiempo(Integer tiempo) {
this.tiempo = tiempo;
}
public void addAcceso(Date d){
this.accesos.addLast(d);
}
}
//Archivo Archivo.java
package contador;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
13
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Genera un objeto para abrir archvios y validar su formato o extención.
* Permite generar todos los recursos para la lectura de los archivos de
* Excel 2003 o anterior.
* @author Alberto Mendoza
*/
public class Archivo {
private String ruta; //almacena la ubicación del archivo
private String nombre; //almacena el nombre del archivo con su extención
private TipoExcel tipo; //variable de tipo enumerado que indica el tipo de archivo seleccionado.
HSSFWorkbook xls; //archivo de tipo XLS
HSSFSheet shXLS; //hoja de cálculo de Excel 2003
Iterator<Row> rXLS; //iterador de filas de Excel 2003
Iterator<Cell> cXLS;//iterador de celdas de una fila
XSSFWorkbook xlsx; //archivo de tipo XLSX
XSSFSheet shXLSX; //hoja de cálculo de Excel 2007
Iterator<Row> rXLSX; //iterador de filas de Excel 2007
Iterator<Cell> cXLSX;//iterador de celdas de una fila
String celda; //alamcena el contenido de una celda en texto
private String extension; //almacena la extención del archivo
//variables auxiliares
String[] archivo; //se usa para determinar el tipo de archvio
14
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
String ext; //variable temporal para almacenar la extención del archivo
String temp; //variable de uso general
/**
* Constructor nulo. No abre ningún archivo, solo inicializa el objeto
*/
public Archivo() {
this.ruta = "";
this.nombre = this.separarNombreArchivo();
this.tipo = null;
this.celda = "";
this.extension = "";
this.archivo = null;
this.ext = "";
this.temp = "";
}
/**
* Constructor que recibe la ruta del archivo y obtiene el nombre del archivo.
* Abre el archivo de excel y se inicializan las instancias que permiten el
* acceso al contenido.
* @param path
*/
public Archivo(String path) {
this.ruta = path;
this.nombre = this.separarNombreArchivo();
this.tipo = null;
15
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
this.celda = "";
this.extension = "";
this.archivo = null;
this.ext = "";
this.temp = "";
this.abrirArchivo();
}
/**
* Regresa el nombre del archivo en caso de que la ruta ya se haya dado, en
* caso contrario regresará un valor nulo.
* @return ret
*/
private String separarNombreArchivo() {
String ret = null;
String tokens[];
tokens = this.ruta.split("\\u005C");
ret = tokens[tokens.length - 1];
tokens = null;
return ret;
}
/**
* Permite abrir el archivo, ya sea XLS o XLXS, con la condición de que la
* ruta del archivo ya se haya dado, en caso contrario mostrará un error.
* Regresa el reporte generado en este método.
* @return reporteArchivo
16
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
* @throws Error
*/
public void abrirArchivo() throws Error {
//boolean valido = false;
determinaTipoDeArchivo();
if (this.tipo == TipoExcel.XLS) {
this.abrirArchivoXLS();
//valido = true;
} else {
System.out.println("Error. Archivo INVÁLIDO.");
}
//return valido;
}
public static boolean validaArchivo(String r){
boolean valido = false;
//create a POIFSFileSystem object to read the data
POIFSFileSystem fs;
FileInputStream fis;
try {
fis = new FileInputStream(r);
fs = new POIFSFileSystem(fis);
} catch (FileNotFoundException ex) {
System.out.println("El archivo seleccionado no se puede encontrar, verifique el nombre y la ruta
del archivo.");
} catch (IOException e) {
17
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
System.out.println("No se puede generar el Stream del archivo de Excel 2003. " + r);
}
return valido;
}
/**
* Abre un archivo de formato MS Office Excel 2003 o anterior. Solo lo abre si ya se ha validado su
formato.
* @throws FileNotFoundException
* @throws IOException
*/
private void abrirArchivoXLS() throws Error {
//create a POIFSFileSystem object to read the data
POIFSFileSystem fs;
FileInputStream fis;
try {
fis = new FileInputStream(this.getRuta());
fs = new POIFSFileSystem(fis);
} catch (FileNotFoundException ex) {
throw new Error("El archivo seleccionado no se puede encontrar, verifique el nombre y la ruta del
archivo.");
} catch (IOException e) {
throw new Error("No se puede generar el Stream del archivo de Excel 2003. " + this.getNombre());
}
try {
// creamos un objeto que contiene los datos del archivo XLS.
this.xls = new HSSFWorkbook(fs);
18
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
// obtenemos la primer hoja de cálculo del archivo.
this.shXLS = this.xls.getSheetAt(0);
//creamos el objeto que permite recorrer todas las filas de la hoja.
this.rXLS = this.shXLS.rowIterator();
} catch (IOException ex) {
throw new Error("No se puede abrir el archivo de Excel 2003. " + this.getNombre());
}
}
/**
* Determina el tipo de archivo que se ha seleccionado. El tipo de archivo es ENUM
(XLS,XLSX,NoValido).
* Esto sucede solo en el caso de que se tenga la ruta y el nombre del archivo.
*/
private void determinaTipoDeArchivo() {
archivo = null;
extension = null;
archivo = nombre.split("\\u002E"); //almacena los tokens del nombre del archivo
// convertimos los tokens a mayúsculas para uniformar las comparaciones
for (int i = 0; i < archivo.length; i++) {
archivo[i] = archivo[i].toUpperCase();
}
ext = archivo[archivo.length - 1];
extension = ext;
//comparamos cuál es el tipo de archivo que se proporcionó
if (extension.equals("XLS")) {
19
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
tipo = TipoExcel.XLS; // el archivo es de Excel 2003 o anterior
} else {
if (extension.equals("XLSX")) {
tipo = TipoExcel.XLSX; // el archivo es de Excel 2007
} else {
tipo = TipoExcel.NoValido;
}
}
}
/**
* Extrae los datos de un archivo de Excel, lo almacena en formato de
* arreglo y regresa esos datos como un objeto de tipo LinkedList<Alumno>
*/
public LinkedList<Informe> getDataInforme() {
LinkedList<Informe> d = new LinkedList<Informe>(); //almacena los datos a extrer del archivo de
excel
String cur = "", nom = "", dirIP = "", acc = "", info = "";
Date fecha = new Date();
//Informe reg = new Informe(); // clase para guardar los datos en 'd'
Row fila = null;
//recorremos dos filas hacia abajo
this.rXLS.next();//posición: primera fila
this.rXLS.next();//posición: segunda fila
//posicionados en la 3a fila extraemos los datos
while (this.rXLS.hasNext()) {
20
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
fila = this.rXLS.next();
cur = fila.getCell(0).getStringCellValue();
fecha = fila.getCell(1).getDateCellValue();
dirIP = fila.getCell(2).getStringCellValue();
nom = fila.getCell(3).getStringCellValue();
acc = fila.getCell(4).getStringCellValue();
try {
info = fila.getCell(5).getStringCellValue();
} catch (Exception e) {
info = "";
}
d.addFirst(new Informe(cur, fecha, dirIP, nom, acc, info));
}
return d;
}
/**
* Establece la ruta del archivo
* @param ruta
*/
public void setRuta(String ruta) {
this.ruta = ruta;
}
/**
* regresa la ruta en donde se encuentra almacenado el archivo
* @return ruta
21
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
*/
public String getRuta() {
return ruta;
}
/**
* regresa el nombre del archivo especificado
* @return nombre
*/
public String getNombre() {
return nombre;
}
/**
* establece el nombre del archivo
* @param nombre
*/
private void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* el tipo de formato del archivo especificado.
* @return tipo
*/
public TipoExcel getTipo() {
return tipo;
}
22
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
/**
* Almacena todos los valores de las celdas.
* @return celda
*/
public String getCelda() {
return this.celda;
}
/**
* La extención del archivo en mayúsculas.
* @return extension
*/
public String getExtension() {
return extension;
}
/**
* Establece la extensión del archivo
* @param nextension
*/
public void setExtension(String nextension) {
this.extension = nextension;
}
}
//Archivo Contador.java
package contador;
import java.util.Date;
23
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
import java.util.LinkedHashMap;
import java.util.LinkedList;
import javax.swing.JTable;
/**
*
* @author Alberto
*/
public class Contador {
JTable tiempos;
private Integer tiempoTotal;
long numReg;
Archivo datos;
LinkedHashMap alumnos;
String curso;
public Contador() {
}
public JTable calcTiempos(String ruta) {
this.datos = new Archivo(ruta); //abrimos el archivo
LinkedList<Informe> info = this.datos.getDataInforme(); //se obtienen los datos del informe
this.numReg = (long) info.size();
this.alumnos = this.informeToAlumnos(info);//juntamos
this.generaTabla();
return this.tiempos;
}
private LinkedHashMap informeToAlumnos(LinkedList<Informe> info) {
24
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
LinkedHashMap ret = new LinkedHashMap(); // alumnos con accesos (sin repetir alumnos)
String key = ""; // almacena el nombre del alumno, es la clave del mapa
Acceso accs = new Acceso(); //instancia que registra los accesos
LinkedList<Date> acc = new LinkedList<Date>(); // lista de accesos, es contenida en la clase Acceso
// se procede al llenado del mapa, o los registros
for (int i = 0; i < info.size(); i++) {
accs = new Acceso();
key = info.get(i).getNombre(); //se obtiene el nombre (key)
if (!ret.containsKey(key)) { // si no existe el nombre en el mapa...
accs.addAcceso(info.get(i).getFecha()); //generamos su primer valor, o acceso
} else { // ... si no ...
accs = (Acceso) ret.get(key); //obtenemos los valores de la clave (key)
accs.addAcceso(new Date(info.get(i).getFecha().getTime())); // agregamos el acceso actual
(actualizar)
}
ret.put(key, accs); //guardamos los datos en el mapa.
}
// se calcula el tiempo invertido por cada alumno (key) del mapa
this.tiempoTotal = new Integer(0);
Object[] keys = ret.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
key = (String) keys[i];
accs = (Acceso) ret.get(key); //se obtienen los valores del alumno (accesos y tiempo), o sea una
instancia de Acceso
acc = accs.getAccesos(); //se obtienen los accesos de la instacia.
//se calculan los intervalos entre cada acceso para sumarlos.
25
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
Long int1 = new Long(0), int2 = new Long(0), intervalo = new Long(0);
for (int j=1 ; j<acc.size() ; j++){
int1 = acc.get(j).getTime(); //acc.get(j).getTime();
int2 = acc.get(j-1).getTime();
intervalo = int1 - int2; //intervalo en milisegundos.
if (intervalo > 1800000) // si el intervalo es mayo a 30 minutos...
accs.setTiempo(accs.getTiempo() + 1800000); // ...se suman 30 minutos
else // ... si no ...
accs.setTiempo(accs.getTiempo() + intervalo.intValue()); // ... se suma el intervalo.
}
this.tiempoTotal += accs.getTiempo()/60000;
ret.put(key, accs);
}
this.curso = info.get(0).getCurso();// se determina el nombre del curso.
return ret; // se retornan los resultados del cálculos de los tiempos. Nombre y tiempo total
invertido.
}
private void generaTabla() {
Tabla mod = new Tabla();
String[] nomColum = mod.getColumnNames(); //nombres de las comlumnas
//generamos las cadenas a mostrar, a partir de el 'mapa alumnos'
Object[] keys = alumnos.keySet().toArray();
int keysLong = keys.length;
Object[][] datosTabla = new Object[keysLong][4];
Acceso acc;
26
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
String key = "", t = "";
for (int i=0 ; i<keys.length ; i++){
datosTabla[i][0] = this.getCurso();
datosTabla[i][1] = String.valueOf(i+1);//cbs[i]; //almacena el checkbox el 'No.'
key = (String) keys[i];
datosTabla[i][2] = key; //almacena el nombre
acc = new Acceso();
acc = (Acceso) alumnos.get(key);
t = String.valueOf((acc.getTiempo().intValue())/60000);
datosTabla[i][3] = t; //almacena el tiempo
}
// creamos la tabla con los 'datos' y con los nombres de columnas 'nomColum'
this.tiempos = new JTable(datosTabla,nomColum);
}
/**
* @return the tiempoTotal
*/
public Integer getTiempoTotal() {
return tiempoTotal;
}
/**
* @param tiempoTotal the tiempoTotal to set
*/
public void setTiempoTotal(Integer tiempoTotal) {
this.tiempoTotal = tiempoTotal;
27
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
}
public String getCurso(){
if (this.curso.length() < 6){
this.determinaCurso();
}
return this.curso;
}
private void determinaCurso() {
if (this.curso.equals("CB01")){
this.curso = "Biología 01";
} else if (this.curso.equals("CB02")){
this.curso = "Biología 02";
}else if (this.curso.equals("CE01")){
this.curso = "Ecología 01";
}else if (this.curso.equals("CE02")){
this.curso = "Ecología 02";
}else if (this.curso.equals("CF01")){
this.curso = "Física 01";
}else if (this.curso.equals("CF02")){
this.curso = "Física 02";
}else if (this.curso.equals("CM01")){
this.curso = "Matemáticas 01";
}else if (this.curso.equals("CM02")){
this.curso = "Matemáticas 02";
}else if (this.curso.equals("CQ01")){
28
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
this.curso = "Química 01";
}else if (this.curso.equals("CQ02")){
this.curso = "Química 02";
} else {
this.curso = "Diplomado";
}
}
}
//Archivo Informe.java
package contador;
import java.util.Date;
/**
*
* @author Alberto
*/
public class Informe {
private String curso;
private Date fecha;
private String direccionIP;
private String nombre;
private String accion;
private String informacion;
public Informe(String curso, Date fecha, String direccionIP, String nombre, String accion, String
informacion){
this.curso = curso;
29
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
this.fecha = fecha;
this.direccionIP = direccionIP;
this.nombre = nombre;
this.accion = accion;
this.informacion = informacion;
}
public Informe(){}
/**
* @return the curso
*/
public String getCurso() {
return curso;
}
/**
* @param curso the curso to set
*/
public void setCurso(String curso) {
this.curso = curso;
}
/**
* @return the fecha
*/
public Date getFecha() {
return fecha;
}
30
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
/**
* @param fecha the fecha to set
*/
public void setFecha(Date fecha) {
this.fecha = fecha;
}
/**
* @return the direccionIP
*/
public String getDireccionIP() {
return direccionIP;
}
/**
* @param direccionIP the direccionIP to set
*/
public void setDireccionIP(String direccionIP) {
this.direccionIP = direccionIP;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
31
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the accion
*/
public String getAccion() {
return accion;
}
/**
* @param accion the accion to set
*/
public void setAccion(String accion) {
this.accion = accion;
}
/**
* @return the informacion
*/
public String getInformacion() {
return informacion;
}
/**
* @param informacion the informacion to set
32
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
*/
public void setInformacion(String informacion) {
this.informacion = informacion;
}
}
//Archivo Tabla.java
package contador;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Alberto
*/
public class Tabla extends AbstractTableModel {
private String[] columnNames = {"Curso", "Número", "Nombre del docente/usuario", "Minutos"};
private Object[][] data = {{" ", " ", " ", " "}};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
33
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
public Object getValueAt(int row, int col) {
return data[row][col];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String[] getColumnNames() {
return this.columnNames;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
//Archivo TipoExcel.java
package contador;
/**
* Clase de tipo ENUM que contiene los tipos de archivo manejados en la aplicación
* @author Alberto Mendoza, Jennifer Paniagua
34
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
*/
public enum TipoExcel {
/**
* Tipo enumerado de un archivo de MS Office Excel 2003 o anterior.
*/
XLS(1),
/**
* Tipo enumerado de un archivo de MS Office Excel 2007
*/
XLSX(2),
/**
* Tipo enumerado para un archivo que no corresponda a un archido de MS
* Office Excel 2007 o anterior.
*/
NoValido(0);
private int tipo;
TipoExcel(int t) {
this.tipo = t;
}
/**
* regresa el tipo ENUM del archivo
* @return the tipo
*/
public int getTipo() {
return tipo;
35
Código fuente. Contador de Tiempo Invertido (por los alumnos de la
plataforma)
}
}
36