/*
* addInternalFrame.java
*
* Created on 2012
* Created by Arsenio Molinero
* Copyright (C) 2012 Arsenio Molinero
*
* GestDB - a Java multi database client
*
* This file is part of GestDB.
*
* GestDB 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.
*
* GestDB 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 GestDB; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.GestDB.sql;
import com.GestDB.Gestor;
import com.GestDB.general.Trackbug;
import com.GestDB.sql.Types.gbBlob;
import com.GestDB.sql.Types.gbClob;
import com.GestDB.sql.Types.gbSQLXML;
import com.GestDB.swing.DatePickerObserver;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.JTextComponent;
import org.netbeans.lib.awtextra.AbsoluteConstraints;
/**
*
* @author seni
*/
public class addInternalFrame extends javax.swing.JInternalFrame {
private Gestor gestor = null;
private ResulsetPannel resulsetPannel = null;
private EstructuraBDPanel estructuraBDPanel = null;
private String sCatalog = null;
private String sSchema = null;
private String sTable = null;
public String jdbcDriverURL=null;
public String jdbcDriverClass=null;
private String user=null;
private String password=null;
private int numRows = 0;
private Vector<HashMap> vResulSet = null;
public addInternalFrame(EstructuraBDPanel estructuraBDPanel, String sCatalog, String sSchema, String sTable,
String jdbcDriverURL,String user1,String password1)
{
this.estructuraBDPanel = estructuraBDPanel;
this.resulsetPannel = null;
this.gestor = estructuraBDPanel.conexionIFrame.padre;
iniciar(sCatalog, sSchema, sTable, jdbcDriverURL, user1, password1);
}
public addInternalFrame(ResulsetPannel resulsetPannel, String sCatalog, String sSchema, String sTable,
String jdbcDriverURL,String user1,String password1)
{
this.estructuraBDPanel = null;
this.resulsetPannel = resulsetPannel;
this.gestor = resulsetPannel.sqlpannel.padre;
iniciar(sCatalog, sSchema, sTable, jdbcDriverURL, user1, password1);
}
/**
* Inicializa la ventana creando tantas cajas de texto como campos tengamos.
*/
private void iniciar(String sCatalog, String sSchema, String sTable, String jdbcDriverURL,String user1,String password1)
{
this.sCatalog = sCatalog;
this.sSchema = sSchema;
this.sTable = sTable;
this.jdbcDriverURL=jdbcDriverURL;
this.user=user1;
this.password=password1;
initComponents();
PonLiterales();
jPanelContenedor.setBackground(this.getBackground());
if(this.sCatalog != null && this.sCatalog.trim().length() == 0)
this.sCatalog = null;
if(this.sSchema != null && this.sSchema.trim().length() == 0)
this.sSchema = null;
// rellenamos la tabla con los datos de la estructuta de la tabla que nos han pasado como parametro
vResulSet = new Vector<HashMap>();
HashMap hmTemp = null;
Connection connection = null;
ResultSet rs = null;
try {
if(user != null && user.trim().length() != 0)
connection = DriverManager.getConnection(jdbcDriverURL, user, password);
else
connection = DriverManager.getConnection(jdbcDriverURL);
// tenemos que buscar el nombre real de la tabla, pues hay bases de datos que son casesensitive y no
// encuentra las columnas de la tabla si no las escribes exactamente igual.
DatabaseMetaData dbmd = connection.getMetaData();
if(resulsetPannel != null)
{
HashMap <String, String>hmtablas = resulsetPannel.sqlpannel.getTablesFromComboBox();
if(hmtablas != null && this.sTable != null && hmtablas.containsKey(this.sTable.toLowerCase()))
this.sTable = hmtablas.get(this.sTable.toLowerCase());
}
// lanzamos la sql para sacar las columnas de la tabla
rs = dbmd.getColumns(this.sCatalog, this.sSchema, this.sTable, null);
numRows = 0;
if(rs != null)
{
while(rs.next())
{
hmTemp = new HashMap(21);
hmTemp.put("COLUMN_NAME", rs.getString("COLUMN_NAME"));
hmTemp.put("DATA_TYPE", rs.getInt("DATA_TYPE")); // SQL type from java.sql.Types
hmTemp.put("DATA_TYPE2", rs.getInt("DATA_TYPE")); // SQL type from java.sql.Types
hmTemp.put("TYPE_NAME", rs.getString("TYPE_NAME")); // Data source dependent type name, for a UDT the type name is fully qualified
hmTemp.put("COLUMN_SIZE", rs.getInt("COLUMN_SIZE"));
hmTemp.put("DECIMAL_DIGITS", rs.getInt("DECIMAL_DIGITS")); // the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable.
hmTemp.put("NUM_PREC_RADIX", rs.getInt("NUM_PREC_RADIX")); // Radix (typically either 10 or 2)
hmTemp.put("NULLABLE", rs.getInt("NULLABLE")); // is NULL allowed
// columnNoNulls - might not allow NULL values
// columnNullable - definitely allows NULL values
// columnNullableUnknown - nullability unknown
hmTemp.put("REMARKS", rs.getString("REMARKS")); // comment describing column (may be null)
hmTemp.put("COLUMN_DEF", rs.getString("COLUMN_DEF")); // default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be null)
hmTemp.put("SQL_DATA_TYPE", rs.getInt("SQL_DATA_TYPE")); // unused
hmTemp.put("SQL_DATETIME_SUB", rs.getInt("SQL_DATETIME_SUB")); // unused
hmTemp.put("CHAR_OCTET_LENGTH", rs.getInt("CHAR_OCTET_LENGTH")); // for char types the maximum number of bytes in the column
hmTemp.put("ORDINAL_POSITION", rs.getInt("ORDINAL_POSITION")); // index of column in table (starting at 1)
hmTemp.put("IS_NULLABLE", rs.getString("IS_NULLABLE")); // ISO rules are used to determine the nullability for a column.
// YES --- if the parameter can include NULLs
// NO --- if the parameter cannot include NULLs
// empty string --- if the nullability for the parameter is unknown
try {
hmTemp.put("SCOPE_CATALOG", rs.getString("SCOPE_CATALOG")); // catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn't REF)
} catch(Exception e)
{
hmTemp.put("SCOPE_CATALOG", null);
}
try {
hmTemp.put("SCOPE_SCHEMA", rs.getString("SCOPE_SCHEMA")); // schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF)
} catch(Exception e)
{
hmTemp.put("SCOPE_CATALOG", null);
}
try {
hmTemp.put("SCOPE_TABLE", rs.getString("SCOPE_TABLE")); // table name that this the scope of a reference attribure (null if the DATA_TYPE isn't REF)
} catch(Exception e)
{
hmTemp.put("SCOPE_TABLE", null);
}
try {
hmTemp.put("SOURCE_DATA_TYPE", rs.getShort("SOURCE_DATA_TYPE")); // source type of a distinct type or user-generated Ref type, SQL type from java.sql.Types (null if DATA_TYPE isn't DISTINCT or user-generated REF)
} catch(Exception e)
{
hmTemp.put("SOURCE_DATA_TYPE", null);
}
try {
hmTemp.put("IS_AUTOINCREMENT", rs.getString("IS_AUTOINCREMENT")); // Indicates whether this column is auto incremented
// YES --- if the column is auto incremented
// NO --- if the column is not auto incremented
// empty string --- if it cannot be determined whether the column is auto incremented parameter is unknown
} catch(Exception e)
{
hmTemp.put("IS_AUTOINCREMENT", "");
}
// si estamos en mysql y es un tipo enumeration o set, tenemos que sacar los valores para meterlos en un combo.
if(hmTemp.containsKey("TYPE_NAME") && (hmTemp.get("TYPE_NAME").toString().equals("ENUM") ||
hmTemp.get("TYPE_NAME").toString().equals("SET")))
{
String cadena = null;
Statement stm1 = null;
ResultSet rs1 = null;
try {
stm1 = connection.createStatement();
rs1 = stm1.executeQuery("SELECT column_type FROM information_schema.COLUMNS WHERE TABLE_NAME = '" + this.sTable + "' AND column_name = '" + hmTemp.get("COLUMN_NAME").toString() + "'");
if(rs1 != null && rs1.next())
{
cadena = rs1.getString(1);
// la cadena puede tener el siguiente aspecto:
// enum('x-small','small','medium','large','x-large')
// set('a','b','c','d')
// quitamos todo lo que hay desde el principio hasta el caracter "(" y el �ltimo caracter ")"
int posCar = cadena.indexOf('(');
if(posCar != -1)
{
cadena = cadena.substring(posCar + 1, cadena.length() - 1);
hmTemp.put("VALUES", cadena);
}
}
} catch(Exception e)
{
;
} finally
{
if(rs1 != null)
{
try { rs1.close(); }catch(Exception e){ ; }
}
if(stm1 != null)
{
try { stm1.close(); }catch(Exception e){ ; }
}
}
}
vResulSet.addElement(hmTemp);
}
numRows = vResulSet.size();
}
Boolean bool[] = { false, true };
Object [][] oRows = new Object[numRows][4];
JTextField jtf = null;
JComboBox jcb = null;
JTextArea jta = null;
JScrollPane jsp = null;
JFormattedTextField jftf = null;
DatePickerObserver dpo = null;
int posY = 0;
int incremento = 22;
Dimension dimTitulo = new Dimension(100,22);
Dimension dimTexto = new Dimension(355,22);
Dimension dimTexto2 = new Dimension(355,88);
Dimension dimTipo = new Dimension(120,22);
Dimension dimTipo2 = new Dimension(88,22);
FocusListener flTextField = new FocusListener(){
public void focusGained(FocusEvent e) {
((JTextField)e.getSource()).selectAll();
}
public void focusLost(FocusEvent e) {
}
};
FocusListener flTextArea = new FocusListener(){
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
String cadena = ((JTextArea)e.getSource()).getText();
if(cadena.length() > 0 && cadena.charAt(cadena.length() - 1) == '\t')
((JTextArea)e.getSource()).setText(cadena.substring(0,cadena.length() - 1));
}
};
KeyListener commandKeyListener = new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if(e.isControlDown() && e.isShiftDown() && e.getKeyCode() == e.VK_ENTER)
{
jbCrearYContinuarActionPerformed(null);
}
else if(e.isControlDown() && e.getKeyCode() == e.VK_ENTER)
{
jbCrearActionPerformed(null);
}
else if(e.getKeyCode() == e.VK_ESCAPE)
{
jbCancelarActionPerformed(null);
}
}
};
class LimiteKeyListener implements KeyListener {
private int limiteDelTexto = -1;
public LimiteKeyListener(int limiteDelTexto)
{
this.limiteDelTexto = limiteDelTexto;
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if(((JTextField)e.getSource()).getText().length() > limiteDelTexto)
{
Toolkit.getDefaultToolkit().beep();
}
}
};
for(int i=0, limite = vResulSet.size(); i < limite; i++)
{
hmTemp = vResulSet.elementAt(i);
if(((String)hmTemp.get("IS_AUTOINCREMENT")).equals("YES") == false)
{
incremento = 22;
JPanel jp = new JPanel();
jp.setLayout(new FlowLayout());
JPanel jp2 = new JPanel(new BorderLayout());
JLabel jl = new JLabel((String)hmTemp.get("COLUMN_NAME"));
jl.setPreferredSize(dimTitulo);
jp2.add(jl,BorderLayout.WEST);
int tiposql = ((Integer)hmTemp.get("DATA_TYPE")).intValue();
if(tiposql == java.sql.Types.OTHER)
{
String type_name = (String)hmTemp.get("TYPE_NAME");
if(type_name.toLowerCase().equals("float") || type_name.toLowerCase().equals("real") || type_name.toLowerCase().equals("double"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.REAL));
tiposql = java.sql.Types.REAL;
}
else if(type_name.toLowerCase().equals("clob"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.CLOB));
tiposql = java.sql.Types.CLOB;
}
else if(type_name.toLowerCase().equals("nclob"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.NCLOB));
tiposql = java.sql.Types.NCLOB;
}
else if(type_name.toLowerCase().equals("blob"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.BLOB));
tiposql = java.sql.Types.BLOB;
}
else if(type_name.toLowerCase().equals("nvarchar2"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.NVARCHAR));
tiposql = java.sql.Types.NVARCHAR;
}
else if(type_name.toLowerCase().equals("nchar"))
{
hmTemp.put("DATA_TYPE2", String.valueOf(java.sql.Types.NCHAR));
tiposql = java.sql.Types.NCHAR;
}
}
switch(tiposql)
{
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
jcb = new JComboBox(bool);
jcb.setOpaque(true);
jcb.setPreferredSize(dimTexto);
jcb.addKeyListener(commandKeyListener);
jp2.add(jcb,BorderLayout.CENTER);
hmTemp.put("contenido", jcb);
jl = new JLabel(hmTemp.get("TYPE_NAME").toString());
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.NUMERIC:
case java.sql.Types.REAL:
NumberFormat nf = NumberFormat.getNumberInstance();
if(jdbcDriverURL.indexOf("cubrid") == -1) // si no es cubrid ponemos los limites, cubrid retorna siempre 0
{
nf.setMaximumIntegerDigits(((Integer)hmTemp.get("COLUMN_SIZE")).intValue());
nf.setMaximumFractionDigits(((Integer)hmTemp.get("DECIMAL_DIGITS")).intValue());
}
nf.setRoundingMode(RoundingMode.FLOOR);
jftf = new JFormattedTextField (nf);
jftf.setPreferredSize(dimTexto);
jftf.addFocusListener(flTextField);
jftf.addKeyListener(commandKeyListener);
jp2.add(jftf,BorderLayout.CENTER);
hmTemp.put("contenido", jftf);
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (" + hmTemp.get("COLUMN_SIZE") + "," + hmTemp.get("DECIMAL_DIGITS") + ")");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.INTEGER:
case java.sql.Types.ROWID:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
nf = NumberFormat.getNumberInstance();
int tamanioColumna = Math.max(((Integer)hmTemp.get("COLUMN_SIZE")).intValue(), 3);
nf.setMaximumIntegerDigits(tamanioColumna);
nf.setMaximumFractionDigits(0);
jftf = new JFormattedTextField (nf);
jftf.setPreferredSize(dimTexto);
jftf.addFocusListener(flTextField);
jftf.addKeyListener(commandKeyListener);
jp2.add(jftf,BorderLayout.CENTER);
hmTemp.put("contenido", jftf);
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (" + hmTemp.get("COLUMN_SIZE") + ")");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.BIGINT:
nf = NumberFormat.getNumberInstance();
tamanioColumna = Math.max(((Integer)hmTemp.get("COLUMN_SIZE")).intValue(), 19);
nf.setMaximumIntegerDigits(tamanioColumna);
nf.setMaximumFractionDigits(0);
jftf = new JFormattedTextField (nf);
jftf.setValue(new Long(0));
jftf.setPreferredSize(dimTexto);
jftf.addFocusListener(flTextField);
jftf.addKeyListener(commandKeyListener);
jp2.add(jftf,BorderLayout.CENTER);
hmTemp.put("contenido", jftf);
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (" + hmTemp.get("COLUMN_SIZE") + ")");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
DateFormatter df = new DateFormatter(DateFormat.getDateInstance());
if(tiposql == java.sql.Types.TIME)
df = new DateFormatter(DateFormat.getTimeInstance());
else if(tiposql == java.sql.Types.TIMESTAMP || jdbcDriverURL.indexOf("oracle") != -1)
df = new DateFormatter(DateFormat.getDateTimeInstance());
if(tiposql != java.sql.Types.TIME)
{
dpo = new DatePickerObserver (df);
dpo.setValue(new Date());
dpo.setPreferredSize(dimTexto);
dpo.jtf.addFocusListener(flTextField);
dpo.jtf.addKeyListener(commandKeyListener);
jp2.add(dpo,BorderLayout.CENTER);
hmTemp.put("contenido", dpo.jtf);
}
else
{
jftf = new JFormattedTextField (df);
jftf.setValue(new Date());
jftf.setPreferredSize(dimTexto);
jftf.addFocusListener(flTextField);
jftf.addKeyListener(commandKeyListener);
jp2.add(jftf,BorderLayout.CENTER);
}
jl = new JLabel(hmTemp.get("TYPE_NAME").toString());
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.DATALINK:
String type_name = (String)hmTemp.get("TYPE_NAME");
if((type_name.equals("ENUM") || type_name.equals("SET")) && hmTemp.containsKey("VALUES"))
{
// tenemos que poner los datos en un combo vienen con el siguiente formato
// 'x-small','small','medium','large','x-large'
String cadenas[] = hmTemp.get("VALUES").toString().replaceAll("\'", "").split(",");
jcb = new JComboBox(cadenas);
jcb.setOpaque(true);
jcb.setPreferredSize(dimTexto);
jcb.addKeyListener(commandKeyListener);
jp2.add(jcb,BorderLayout.CENTER);
hmTemp.put("contenido", jcb);
}
else
{
jtf = new JTextField ();
jtf.setPreferredSize(dimTexto);
jtf.addFocusListener(flTextField);
jtf.addKeyListener(new LimiteKeyListener(((Integer)hmTemp.get("COLUMN_SIZE")).intValue()));
jtf.addKeyListener(commandKeyListener);
jp2.add(jtf,BorderLayout.CENTER);
hmTemp.put("contenido", jtf);
}
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (" + hmTemp.get("COLUMN_SIZE") + ")");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
case java.sql.Types.OTHER:
case java.sql.Types.NULL:
case java.sql.Types.STRUCT:
case java.sql.Types.REF:
case java.sql.Types.JAVA_OBJECT:
case -13: // BFILE
jtf = new JTextField ("Not supported");
jtf.setPreferredSize(dimTexto);
jtf.addFocusListener(flTextField);
jtf.addKeyListener(commandKeyListener);
jp2.add(jtf,BorderLayout.CENTER);
hmTemp.put("contenido", jtf);
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (Not supported)");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
default:
incremento = 88;
jsp = new JScrollPane();
jsp.setPreferredSize(dimTexto2);
jta = new JTextArea();
jta.addKeyListener(new java.awt.event.KeyListener(){
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_TAB && e.isShiftDown())
{
((JTextArea)e.getSource()).transferFocusBackward();
}
else if(e.getKeyCode() == e.VK_TAB)
{
((JTextArea)e.getSource()).transferFocus();
}
}
public void keyReleased(KeyEvent e) {
}
});
jta.addKeyListener(commandKeyListener);
jta.addFocusListener(flTextArea);
jsp.setViewportView(jta);
jp2.add(jsp,BorderLayout.CENTER);
hmTemp.put("contenido", jta);
jl = new JLabel(hmTemp.get("TYPE_NAME") + " (" + hmTemp.get("COLUMN_SIZE") + ")");
jl.setPreferredSize(dimTipo);
jp2.add(jl,BorderLayout.EAST);
break;
}
jp.add(jp2);
jPanelContenedor.add(jp,new AbsoluteConstraints(0,posY));
posY += incremento;
}
} // fin del for
} catch(Exception e)
{
com.GestDB.swing.Alerta al = new com.GestDB.swing.Alerta(new javax.swing.JDialog(),
Gestor.GetLiteral("gestor.error","Error"), true,
e.getMessage(), com.GestDB.swing.Alerta.OK);
e.printStackTrace();
al.setVisible(true);
} finally
{
try {
if(rs != null)
rs.close();
} catch (Exception e) { ; }
try {
if(connection != null)
connection.close();
} catch (Exception e) { ; }
}
}
public void PonLiterales()
{
setTitle(Gestor.GetLiteral("addInternalFrame.title","Crear registro"));
jbCrear.setText(Gestor.GetLiteral("selectconexion.create","Crear") + " (Ctrl+Enter)");
jbCrearYContinuar.setText(Gestor.GetLiteral("selectconexion.create_and_continue","Crear y continuar") + " (Ctrl+shift+Enter)");
jbCancelar.setText(Gestor.GetLiteral("importardlg.cancel","Cancelar") + " (Esc)");
}
/**
* Comprueba si hemos introducido un valor en el componente swing correspondiente a la columna que se nos pasa en el hashmap.
* @param hColumna hashMap con los tipos SQL, y los componentes swing de cada columna.
* @return true si hemos introduccido informaci�n
*/
private boolean hasContent(HashMap hColumna)
{
Object obj = hColumna.get("contenido");
String sValor = null;
try {
if(obj instanceof JTextArea)
{
sValor = ((JTextArea)hColumna.get("contenido")).getText();
}
else if(obj instanceof JFormattedTextField)
{
sValor = ((JFormattedTextField)hColumna.get("contenido")).getText();
}
else if(obj instanceof JTextField)
{
sValor = ((JTextField)hColumna.get("contenido")).getText();
}
else if(obj instanceof JComboBox)
{
Object ovalor = (((JComboBox)hColumna.get("contenido"))).getSelectedItem();
if(ovalor instanceof Boolean)
sValor = ((Boolean) ovalor).toString();
else
sValor = ovalor.toString();
}
if(sValor != null && sValor.trim().length() > 0)
{
return true;
}
} catch(Exception e)
{
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, e);
}
return false;
}
/**
* A�ade un objeto al preparestatment acorde con el tipo sql.
* @param stmt preparestatment a utilizar.
* @param hColumna hashMap con los tipos SQL, y los componentes swing de cada columna.
* @param indice Columna a tratar, la primera columna empieza por 1.
*/
private void appendObjectFromTypeSQL(PreparedStatement stmt, HashMap hColumna, int indice)
{
int dataType = Integer.parseInt(hColumna.get("DATA_TYPE").toString());
String dataTypeSQL = (String)hColumna.get("TYPE_NAME");
Object obj = hColumna.get("contenido");
Object oValor = null;
String sValor = null;
try {
boolean bEsCubrid = jdbcDriverURL.contains("cubrid");
if(obj instanceof JTextArea)
{
oValor = sValor = ((JTextArea)hColumna.get("contenido")).getText();
}
else if(obj instanceof JFormattedTextField)
{
oValor = ((JFormattedTextField)hColumna.get("contenido")).getValue();
sValor = ((JFormattedTextField)hColumna.get("contenido")).getText();
}
else if(obj instanceof JTextField)
{
oValor = sValor = ((JTextField)hColumna.get("contenido")).getText();
}
else if(obj instanceof JComboBox)
{
oValor = (((JComboBox)hColumna.get("contenido"))).getSelectedItem();
if(oValor instanceof Boolean)
sValor = ((Boolean) (((JComboBox)hColumna.get("contenido")).getSelectedItem())).toString();
else
sValor = oValor.toString();
}
if(sValor.trim().length() == 0)
{
if(dataType != java.sql.Types.OTHER)
{
stmt.setNull(indice, dataType);
}
else
{
stmt.setNull(indice, dataType, dataTypeSQL);
}
return;
}
switch (dataType) {
case java.sql.Types.DATALINK:
stmt.setURL(indice, new URL(sValor));
break;
case java.sql.Types.BLOB:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setBlob(indice, new gbBlob(sValor).getBinaryStream(), sValor.length());
else
stmt.setBlob(indice, (Blob)getlobOracle(stmt.getConnection(), false, sValor, 2));
break;
case java.sql.Types.NCLOB:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setNClob(indice, new gbClob(sValor).getCharacterStream(), sValor.length());
else
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setClob(indice, (Clob)getlobOracle(stmt.getConnection(), false, sValor, 1));
}
break;
case java.sql.Types.CLOB:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setClob(indice, new gbClob(sValor).getCharacterStream(), sValor.length());
else
stmt.setClob(indice, (Clob)getlobOracle(stmt.getConnection(), false, sValor, 0));
break;
case java.sql.Types.OTHER:
if(dataTypeSQL.toLowerCase().equals("float") || dataTypeSQL.toLowerCase().equals("real") || dataTypeSQL.toLowerCase().equals("double"))
{
stmt.setObject(indice, oValor);
break;
}
else if(dataTypeSQL.toLowerCase().equals("clob"))
{
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setClob(indice, new gbClob(sValor).getCharacterStream(), sValor.length());
else
stmt.setClob(indice, (Clob)getlobOracle(stmt.getConnection(), false, sValor, 0));
break;
}
else if(dataTypeSQL.toLowerCase().equals("nclob"))
{
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setNClob(indice, new gbClob(sValor).getCharacterStream(), sValor.length());
else
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setClob(indice, (Clob)getlobOracle(stmt.getConnection(), false, sValor, 1));
}
break;
}
else if(dataTypeSQL.toLowerCase().equals("blob"))
{
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setBlob(indice, new gbBlob(sValor).getBinaryStream(), sValor.length());
else
stmt.setBlob(indice, (Blob)getlobOracle(stmt.getConnection(), false, sValor, 2));
break;
}
else if(dataTypeSQL.toLowerCase().equals("nvarchar2"))
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setString(indice, sValor);
break;
}
else if(dataTypeSQL.toLowerCase().equals("nchar"))
{
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
{
stmt.setNString(indice, sValor);
}
else
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setString(indice, sValor);
break;
}
}
// else if(sValor != null && sValor.trim().length() > 0 && sValor.trim().equals("Not supported") == false &&
// (dataTypeSQL.toLowerCase().equals("set") || dataTypeSQL.toLowerCase().equals("multiset") ||
// dataTypeSQL.toLowerCase().equals("list") || dataTypeSQL.toLowerCase().equals("sequence")))
// {
// // se comprueba si tenemos las llaves de apertura y cierre, de no tenerlas hay que ponerselas.
// if(bEsCubrid && sValor.trim().charAt(0) != '{')
// sValor = "CAST( {" + sValor + "} as " + dataTypeSQL + ")";
// else if(bEsCubrid)
// sValor = "CAST( " + sValor + " as " + dataTypeSQL + ")";
// stmt.setString(indice, sValor);
// break;
// }
case java.sql.Types.NULL:
case java.sql.Types.STRUCT:
case java.sql.Types.REF:
case java.sql.Types.JAVA_OBJECT:
stmt.setNull(indice, dataType);
break;
case java.sql.Types.LONGNVARCHAR:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setNCharacterStream(indice, new InputStreamReader(new ByteArrayInputStream(sValor.getBytes())));
else
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setAsciiStream(indice, new ByteArrayInputStream(sValor.getBytes()), sValor.length());
}
break;
case java.sql.Types.LONGVARCHAR:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
stmt.setCharacterStream(indice, new InputStreamReader(new ByteArrayInputStream(sValor.getBytes())));
else
stmt.setAsciiStream(indice, new ByteArrayInputStream(sValor.getBytes()), sValor.length());
break;
case java.sql.Types.LONGVARBINARY:
stmt.setBinaryStream(indice, new ByteArrayInputStream(sValor.getBytes()), sValor.length());
break;
case java.sql.Types.SQLXML:
stmt.setSQLXML(indice, new gbSQLXML(sValor));
break;
case java.sql.Types.BIGINT:
stmt.setBigDecimal(indice, new BigDecimal((Long)oValor));
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
stmt.setBoolean(indice, (Boolean) oValor);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
stmt.setObject(indice, new Timestamp(((java.util.Date)oValor).getTime()));
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.NUMERIC:
case java.sql.Types.REAL:
case java.sql.Types.INTEGER:
case java.sql.Types.ROWID:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
stmt.setObject(indice, oValor);
break;
case java.sql.Types.NCHAR:
case java.sql.Types.NVARCHAR:
if(jdbcDriverURL.indexOf("oracle") == -1) // en oracle tenemos un error
{
stmt.setNString(indice, sValor);
break;
}
else
{
// tenemos que indicar el formchar
SetFormOfUseNationalOracle(stmt, indice);
stmt.setString(indice, sValor);
break;
}
case java.sql.Types.VARBINARY:
case java.sql.Types.BINARY:
stmt.setBytes(indice, sValor.getBytes());
break;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
if(dataTypeSQL.toUpperCase().charAt(0) == 'N' && jdbcDriverURL.indexOf("cubrid") == -1) // miramos si es un NCHAR o equivalente. En algunos gestorios los retornan como char o varchar.
{
stmt.setNString(indice, sValor);
break;
}
case java.sql.Types.ARRAY:
case java.sql.Types.DISTINCT:
default:
stmt.setString(indice, sValor);
break;
}
} catch (Exception ex)
{
Trackbug.error(ex, "error en tipo columna " + hColumna.get("DATA_TYPE").toString() + ", clase: " + oValor.getClass().getName() + ", error: " + ex.getMessage());
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
try {
if(dataType != java.sql.Types.OTHER)
{
stmt.setNull(indice, dataType);
}
else
{
String type_name = (String)hColumna.get("TYPE_NAME");
stmt.setNull(indice, dataType, type_name);
}
} catch (Exception ex1) {
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
/** 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">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jPanelContenedor = new javax.swing.JPanel();
jbCrearYContinuar = new javax.swing.JButton();
jbCancelar = new javax.swing.JButton();
jbCrear = new javax.swing.JButton();
setClosable(true);
setMaximizable(true);
setResizable(true);
jScrollPane2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jPanelContenedor.setBackground(new java.awt.Color(255, 255, 255));
jPanelContenedor.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jScrollPane2.setViewportView(jPanelContenedor);
jbCrearYContinuar.setText("Crear y continuar");
jbCrearYContinuar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCrearYContinuarActionPerformed(evt);
}
});
jbCancelar.setText("Cancelar");
jbCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCancelarActionPerformed(evt);
}
});
jbCrear.setText("Crear");
jbCrear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCrearActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jbCrear)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbCrearYContinuar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbCancelar)
.addContainerGap(350, Short.MAX_VALUE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbCrear)
.addComponent(jbCrearYContinuar)
.addComponent(jbCancelar))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Acci�n lanzada cuando pulsan el bot�n jbCancelar, que cancela la creaci�n
* @param evt Evento del bot�n
*/
private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jbCancelarActionPerformed
{//GEN-HEADEREND:event_jbCancelarActionPerformed
this.setVisible(false);
if(estructuraBDPanel != null)
estructuraBDPanel.CargarDatos(sTable);
else
resulsetPannel.doQuery();
gestor.DesktopPanel.remove(this);
}//GEN-LAST:event_jbCancelarActionPerformed
/**
* Acci�n lanzada cuando pulsan el bot�n jbCrear, que permite crear el registro.
* @param evt Evento del bot�n
*/
private void jbCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCrearActionPerformed
if(crearRegistro())
{
this.setVisible(false);
if(estructuraBDPanel != null)
estructuraBDPanel.CargarDatos(sTable);
else
resulsetPannel.doQuery();
gestor.DesktopPanel.remove(this);
}
}//GEN-LAST:event_jbCrearActionPerformed
/**
* Acci�n lanzada cuando pulsan el bot�n jbCrearYContinuar, que permite crear el registro y continuar creando otro
* @param evt Evento del bot�n
*/
private void jbCrearYContinuarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCrearYContinuarActionPerformed
if(crearRegistro())
{
HashMap hColumna = null;
for(int i = 0, j = 0; i < numRows; i++)
{
hColumna = vResulSet.elementAt(i);
Object obj = hColumna.get("contenido");
try {
if(obj != null)
{
if(obj instanceof JTextArea)
{
((JTextArea)hColumna.get("contenido")).setText("");
}
else if(obj instanceof JFormattedTextField)
{
((JFormattedTextField)hColumna.get("contenido")).setText("");
}
else if(obj instanceof JTextField)
{
((JTextField)hColumna.get("contenido")).setText("");
}
else if(obj instanceof JComboBox)
{
((JComboBox)hColumna.get("contenido")).setSelectedIndex(-1);
}
}
} catch(Exception e)
{
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, e);
}
}
ponFocoEnElprimero();
}
}//GEN-LAST:event_jbCrearYContinuarActionPerformed
/**
* Pone el foco del rat�n en el primer campo.
*/
private void ponFocoEnElprimero()
{
HashMap hmTemp = null;
for(int i = 0, j = 0; i < numRows; i++)
{
hmTemp = vResulSet.elementAt(i);
if(((String)hmTemp.get("IS_AUTOINCREMENT")).equals("YES") == false)
{
Object obj = hmTemp.get("contenido");
((JTextComponent)obj).grabFocus();
break;
}
}
}
/**
* Crea el registro en la bbdd
* @return true si se ha creado corretamente
*/
private boolean crearRegistro() {
boolean resultado = false;
Connection connection = null;
PreparedStatement stmt = null;
try {
// preparamos el resulsetmetadata
if(user != null && user.trim().length() != 0)
connection = DriverManager.getConnection(jdbcDriverURL, user, password);
else
connection = DriverManager.getConnection(jdbcDriverURL);
String sQuestions = "";
String sNames = "";
HashMap hmTemp = null;
for(int i = 0, j = 0; i < numRows; i++)
{
hmTemp = vResulSet.elementAt(i);
if(((String)hmTemp.get("IS_AUTOINCREMENT")).equals("YES") == false && hasContent(hmTemp))
{
sQuestions += (j > 0 ? ",?" : "?");
sNames += (j > 0 ? "," : "") + hmTemp.get("COLUMN_NAME").toString();
// tenemos que mirar si el campo no permite null y esta vacio para cancelar la operaci�n y avisarlo
if(((Integer)hmTemp.get("NULLABLE")).intValue() == 0)
{
Object obj = hmTemp.get("contenido");
if((obj instanceof JTextField && ((JTextField)hmTemp.get("contenido")).getText().trim().length() == 0) ||
(obj instanceof JTextArea && ((JTextArea)hmTemp.get("contenido")).getText().trim().length() == 0) ||
(obj instanceof JFormattedTextField && ((JFormattedTextField)hmTemp.get("contenido")).getText().trim().length() == 0))
{
com.GestDB.swing.Alerta al = new com.GestDB.swing.Alerta(new javax.swing.JDialog(),
Gestor.GetLiteral("gestor.error","Error"), true,
hmTemp.get("COLUMN_NAME").toString() + " " + Gestor.GetLiteral("addInternalFrame.column_mandatory","es obligatorio"),
com.GestDB.swing.Alerta.OK);
al.setVisible(true);
((JTextComponent)obj).grabFocus();
return resultado;
}
}
++j;
}
}
stmt = connection.prepareStatement("INSERT INTO " + sTable + " ( " + sNames + ") VALUES (" + sQuestions + ")");
for(int i = 0, j = 1; i < numRows; i++)
{
hmTemp = vResulSet.elementAt(i);
if(((String)hmTemp.get("IS_AUTOINCREMENT")).equals("YES") == false && hasContent(hmTemp))
{
// Trackbug.info("Metemos la columna " + ((String)hmTemp.get("COLUMN_NAME")));
appendObjectFromTypeSQL(stmt,hmTemp, j);
++j;
}
}
stmt.executeUpdate();
com.GestDB.swing.Alerta al = new com.GestDB.swing.Alerta(new javax.swing.JDialog(),
Gestor.GetLiteral("gestor.alert","Atenci�n"), true,
Gestor.GetLiteral("addInternalFrame.row_add","Registro creado correctamente"), com.GestDB.swing.Alerta.OK);
resultado = true;
} catch(Exception e)
{
com.GestDB.swing.Alerta al = new com.GestDB.swing.Alerta(new javax.swing.JDialog(),
Gestor.GetLiteral("gestor.error","Error"), true,
e.getMessage(), com.GestDB.swing.Alerta.OK);
e.printStackTrace();
al.setVisible(true);
} finally
{
try {
if(stmt != null)
stmt.close();
} catch (Exception e) { ; }
try {
if(connection != null)
connection.close();
} catch (Exception e) { ; }
}
return resultado;
}
/**
* Crea un objeto clob de oracle
* @param con
* @param cache
* @param cadena
* @param tipo Es el tipo de objeto, puede ser 0: Clob, 1: NClob, 2: blob
* @return
*/
public Object getlobOracle(Connection con, boolean cache, String cadena, int tipo)
{
Object objeto = null;
try {
Class clase = null;
switch(tipo)
{
case 0: // Clob
clase = Class.forName("oracle.sql.CLOB");
break;
case 1: // nclob
clase = Class.forName("oracle.sql.CLOB");
break;
case 2: // blob
clase = Class.forName("oracle.sql.BLOB");
break;
}
// creamos el objeto llamando al m�todo createTemporary
Class partypes[] = new Class[] { Connection.class, boolean.class, Integer.TYPE };
Method metodo = clase.getMethod("createTemporary", partypes);
Object arglist[] = new Object[] { con, new Boolean(cache), new Integer(10) }; // oracle.sql.CLOB.DURATION_SESSION 10
objeto = metodo.invoke(null, arglist);
// metemos el texto en el clob llamado a putString(pos,cadena); o putBytes(int pos ,byte[] bytes);
if(tipo == 2) // blob
{
Class partypes2[] = new Class[] { Long.TYPE, byte[].class };
metodo = objeto.getClass().getMethod("putBytes", partypes2);
Object arglist2[] = new Object[] { new Long(1), cadena.getBytes() };
metodo.invoke(objeto, arglist2);
}
else
{
Class partypes2[] = new Class[] { Long.TYPE, String.class };
metodo = objeto.getClass().getMethod("putString", partypes2);
Object arglist2[] = new Object[] { new Long(1), cadena };
metodo.invoke(objeto, arglist2);
}
/* llamar a un contructor
Constructor ct = clase.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = ct.newInstance(arglist);
*/
} catch (Exception ex) {
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex.getCause());
}
return objeto;
}
/**
* Llama al m�todo setCheckBindTypes de oracle para desactivar el checkeo de tipos
* @param Statement de oracle
* @param Booleano que indica si se activo o desactiva.
*/
private void setCheckBindTypesOracle(PreparedStatement stmt, boolean b)
{
Object objeto = null;
try {
Class clase = Class.forName("oracle.jdbc.OraclePreparedStatement");
// creamos el objeto llamando al m�todo createTemporary
Class partypes[] = new Class[] { boolean.class };
Method metodo = clase.getMethod("setCheckBindTypes", partypes);
Object arglist[] = new Object[] { new Boolean(b) };
objeto = metodo.invoke(stmt, arglist);
} catch (Exception ex) {
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex.getCause());
}
}
private static short FORM_CHAR = 1;
private static short FORM_NCHAR = 2;
/**
* Llama al m�todo setFormOfUse de oracle que permite indicar si el string enviado es normal o national, se utiliza para los nchar, nvarchar, y nclob
* @param stmt Statement de oracle
* @param indice columna a utilizar
*/
private void SetFormOfUseNationalOracle(PreparedStatement stmt, int indice) {
Object objeto = null;
try {
Class clase = Class.forName("oracle.jdbc.OraclePreparedStatement");
// creamos el objeto llamando al m�todo createTemporary
Class partypes[] = new Class[] { Integer.TYPE, Short.TYPE };
Method metodo = clase.getMethod("setFormOfUse", partypes);
Object arglist[] = new Object[] { new Integer(indice), new Short(FORM_NCHAR) };
objeto = metodo.invoke(stmt, arglist);
} catch (Exception ex) {
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(addInternalFrame.class.getName()).log(Level.SEVERE, null, ex.getCause());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPanelContenedor;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton jbCancelar;
private javax.swing.JButton jbCrear;
private javax.swing.JButton jbCrearYContinuar;
// End of variables declaration//GEN-END:variables
}