diff --git a/src/jpkj/Calendar.java b/src/jpkj/Calendar.java new file mode 100644 index 0000000..fa0ef3f --- /dev/null +++ b/src/jpkj/Calendar.java @@ -0,0 +1,133 @@ +package jpkj; + +import java.util.regex.Pattern; +import org.joda.time.DateTime; + +public class Calendar { + + DateTime calendar; + + public DateTime getJoda() { + return this.calendar; + } + + public Calendar() { + this.calendar = new DateTime(); + } + + public Calendar(String data) { + this.calendar = new DateTime(); + this.parse(data); + } + + public void parse(String data) { + data = data.trim(); + if (data.isEmpty()) { + return; + } + String separadorDataHora = " "; + boolean temhora = false; + boolean temdata = false; + temdata = Pattern.matches("([0-9]{2,4})(-|/|\\.)([0-9]{2})(-|/|\\.)([0-9]{2,4})", data.split(separadorDataHora)[0]); + if(data.split(separadorDataHora).length > 1){ + temhora = Pattern.matches(".{9,12}([0-9]{2}):([0-9]{2})(:([0-9]{2})){0,1}", data.split(separadorDataHora)[1]); + } + if (temhora) { + separadorDataHora = data.substring(10, 11); + } + String[] split = data.split(Pattern.quote(separadorDataHora)); + String[] split1 = split[0].split("(-|/|\\.)"); + int ano = 0, mes = 0, dia = 0; + if (temdata) { + if (split1[0].length() == 4) { + ano = Integer.parseInt(split1[0]); + mes = Integer.parseInt(split1[1]); + dia = Integer.parseInt(split1[2]); + } else { + ano = Integer.parseInt(split1[2]); + mes = Integer.parseInt(split1[1]); + dia = Integer.parseInt(split1[0]); + } + } else { + ano = calendar.getYear(); + mes = calendar.getMonthOfYear(); + dia = calendar.getDayOfMonth(); + } + int hora = 0, minuto = 0, segundo = 0; + if (temhora) { + String[] split2 = split[1].split(":"); + hora = Integer.parseInt(split2[0]); + minuto = Integer.parseInt(split2[1]); + if (split2.length == 3) { + segundo = Integer.parseInt(split2[3]); + } else { + segundo = 0; + } + } else { + hora = calendar.getHourOfDay(); + minuto = calendar.getMinuteOfHour(); + segundo = calendar.getSecondOfMinute(); + } + this.calendar = new DateTime(ano, mes, dia, hora, minuto, segundo); + } + + public void modify(String value) { + String[] fofinho = value.split(Pattern.quote(" ")); + for (int i = 0; i < fofinho.length; i++) { + String type = fofinho[i]; + i++; + int v = Integer.parseInt(fofinho[i]); + i++; + String mod = fofinho[i]; + if (type.equalsIgnoreCase("+")) { + if (mod.equalsIgnoreCase("DAYS")) { + calendar = calendar.plusDays(v); + } else if (mod.equalsIgnoreCase("MONTHS")) { + calendar = calendar.plusMonths(v); + } else if (mod.equalsIgnoreCase("YEARS")) { + calendar = calendar.plusYears(v); + } else if (mod.equalsIgnoreCase("HOURS")) { + calendar = calendar.plusHours(v); + } else if (mod.equalsIgnoreCase("MINUTES")) { + calendar = calendar.plusMinutes(v); + } else if (mod.equalsIgnoreCase("SECONDS")) { + calendar = calendar.plusSeconds(v); + } + } else if (type.equalsIgnoreCase("-")) { + if (mod.equalsIgnoreCase("DAYS")) { + calendar = calendar.minusDays(v); + } else if (mod.equalsIgnoreCase("MONTHS")) { + calendar = calendar.minusMonths(v); + } else if (mod.equalsIgnoreCase("YEARS")) { + calendar = calendar.minusYears(v); + } else if (mod.equalsIgnoreCase("HOURS")) { + calendar = calendar.minusHours(v); + } else if (mod.equalsIgnoreCase("MINUTES")) { + calendar = calendar.minusMinutes(v); + } else if (mod.equalsIgnoreCase("SECONDS")) { + calendar = calendar.minusSeconds(v); + } + } + + } + } + + /** + * + * @param format yyyy = year MM = month dd =day HH = hour mm = minute ss = + * seconds SSS = microsegunds ZZ = timezone + * @return formated string + */ + public String format(String format) { + String retorno = ""; + retorno = this.calendar.toString(format); + return retorno; + } + + public String format(String format,String mod) { + this.modify(mod); + String retorno = ""; + retorno = this.calendar.toString(format); + return retorno; + } +} diff --git a/src/jpkj/Console.java b/src/jpkj/Console.java new file mode 100644 index 0000000..2047e4a --- /dev/null +++ b/src/jpkj/Console.java @@ -0,0 +1,26 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import java.util.Scanner; + +/** + * + * @author felipe + */ +public class Console { + + public static void write(Object texto) { + System.out.print(texto); + } + + public static void writeLine(Object texto) { + System.out.println(texto); + } + public static String readLine() { + Scanner s = new Scanner(System.in); + return s.nextLine(); + } +} diff --git a/src/jpkj/Db.java b/src/jpkj/Db.java new file mode 100644 index 0000000..ba882b5 --- /dev/null +++ b/src/jpkj/Db.java @@ -0,0 +1,780 @@ +package jpkj; + +import java.io.File; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.sql.*; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.swing.table.*; +import javax.swing.*; +import org.apache.commons.codec.binary.Hex; + +public class Db { + + public static enum Tipos { + + SQLITE, + MYSQL, + HSQLDB, + POSTGRESQL, + FIREBIRD, + ORACLE, + SQLSERVER, + ODBC, + SQLANYWHERE + + }; + + public String Arquivo = ""; + public static Tipos tipo; + public Connection conexao = null; + + public Db ( String url, Properties p ) throws Exception { + this.url = url; + this.usuario = ""; + this.senha = ""; + this.p = p; + this.conexao = Db.newConnection ( url, "", "", p ); + } + + public Db ( String url ) throws Exception { + this.url = url; + this.usuario = ""; + this.senha = ""; + this.p = null; + this.conexao = Db.newConnection ( url ); + } + + public Db ( String url, String usuario, String senha ) throws Exception { + this.url = url; + this.usuario = ""; + this.senha = ""; + this.p = null; + this.conexao = Db.newConnection ( url, usuario, senha, null ); + } + + public void renew () throws Exception { + this.conexao = Db.newConnection ( this.url, this.usuario, this.senha, this.p ); + } + + public Connection getConnection () { + return conexao; + } + + /** + * Método de conexão em geral teste + * + * @param url jdbc:mysql://host:porta/base para odf do libre office use + * odb:caminho + * @param usuario usuário do banco de dados + * @param senha senha do usuário do banco de dados + * @return retorna uma conexão + */ + public void connect ( String url, String usuario, String senha ) throws Exception { + this.conexao = newConnection ( url, usuario, senha, null ); + } + + public void connect ( String url ) throws Exception { + this.conexao = newConnection ( url ); + } + + public static Connection newConnection ( String url ) throws Exception { + return newConnection ( url, "", "", null ); + } + + public String url = ""; + public String usuario = ""; + public String senha = ""; + public Properties p = null; + + /** + * Retorna uma nova conexao + * + * @param url jdbc:mysql://host:porta/base + * @param usuario usuário do banco de dados + * @param senha senha do usuário do banco de dados + * @return retorna uma conexão + */ + public static Connection newConnection ( String url, String usuario, String senha, Properties p ) throws Exception { + Tipos tipo = null; + String classe = "NADA"; + if ( url.contains ( "sqlite" ) ) { + classe = "org.sqlite.JDBC"; + tipo = Tipos.SQLITE; + } + if ( url.contains ( "mysql" ) ) { + classe = "com.mysql.jdbc.Driver"; + tipo = Tipos.MYSQL; + } + if ( url.contains ( "hsqldb" ) ) { + classe = "org.hsqldb.jdbcDriver"; +// if (!tipo.equals("ODB")) { + tipo = Tipos.HSQLDB; +// } + } + if ( url.contains ( "firebird" ) ) { + classe = "org.firebirdsql.jdbc.FBDriver"; + tipo = Tipos.FIREBIRD; + } + if ( url.contains ( "postgre" ) ) { + classe = "org.postgresql.Driver"; + tipo = Tipos.POSTGRESQL; + } + if ( url.contains ( "oracle" ) ) { + classe = "oracle.jdbc.OracleDriver"; + tipo = Tipos.ORACLE; + } + if ( url.contains ( "sqlserver" ) ) { + classe = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + tipo = Tipos.SQLSERVER; + System.out.println ( "A conexão so deve passar a url no seguinte formato.\njdbc:sqlserver://IP.DAMAQUINA:PORTA;databaseName=NOME_DO_DB;user=USUARIO;password=SENHA os outros paramentros serão ignorados" ); + } + if ( url.contains ( "odbc" ) ) { + classe = "sun.jdbc.odbc.JdbcOdbcDriver"; + tipo = Tipos.ODBC; + } + if ( url.contains ( "sqlanywhere" ) ) { + classe = "sybase.jdbc4.sqlanywhere.IDriver"; + tipo = Tipos.SQLANYWHERE; + } + try { + if ( ! classe.equals ( "NADA" ) ) { + Class.forName ( classe ).newInstance (); + } else { + System.out.println ( "Base de dados desconhecida mande um e-mail para felipe@felipeazambuja.com.br" ); + } + } catch ( Exception e ) { + } finally { + + } + if ( p != null ) { + try { + return DriverManager.getConnection ( url, p ); + } catch ( SQLException ex ) { + ex.printStackTrace (); + } finally { + + } + } else { + + if ( tipo.equals ( "SQLSERVER" ) || tipo.equals ( "SQLITE" ) ) { + if ( tipo.equals ( "SQLSERVER" ) ) { + return DriverManager.getConnection ( url ); + } else if ( ! usuario.isEmpty () && ! senha.isEmpty () ) { + return DriverManager.getConnection ( url, usuario, senha ); + } else if ( ! usuario.isEmpty () ) { + return DriverManager.getConnection ( url, usuario, "" ); + } else { + return DriverManager.getConnection ( url ); + } + } else { + return DriverManager.getConnection ( url, usuario, senha ); + } + + } + return null; + } + + /** + * Desconecta a conexao do framework + * + * @param con Conexão a ser fechada. + */ + public void unConnect () { + try { + conexao.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + } + + /** + * Transforma linhas de uma tabela em instruções sql + * + * @param tabela Nome da JTable por exemplo jTable1 + * @param nomeTABELA Nome da tabela do sql por exemplo pessoas + * @param camposSQL Lista com o nome dos campos exemplo new + * String[]{"nome","telefone"}; + * @param camposTABELA Lista com os indices referentes aos campos sql por + * exemplo new int[]{1,2} + * @return Retorna um ArrayList com as instruções SQL. + */ + public static List getSQLTable ( JTable tabela, String nomeTABELA, String[] camposSQL, int[] camposTABELA ) { + List sqls = new List (); + try { + String sql_atual = null; + int quantidade_linhas_tabela = tabela.getRowCount (); + int quantidade_colunas = camposTABELA.length; + for ( int i = 0; i < quantidade_linhas_tabela; i ++ ) { + sql_atual = "insert into " + nomeTABELA + " ("; + for ( int j = 0; j < camposSQL.length; j ++ ) { + if ( j == ( camposSQL.length - 1 ) ) { + sql_atual += camposSQL[ j ] + ") values ("; + } else { + sql_atual += "" + camposSQL[ j ] + ","; + } + } + for ( int j = 0; j < quantidade_colunas; j ++ ) { + if ( j == ( camposSQL.length - 1 ) ) { + sql_atual += tabela.getValueAt ( i, camposTABELA[ j ] ) + ")"; + } else { + sql_atual += "'" + tabela.getValueAt ( i, camposTABELA[ j ] ) + "',"; + } + } + sqls.add ( sql_atual ); + } + return sqls; + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return null; + } + + /** + * Atribui uma tabela um select + * + * @param table jtable + * @param sql string sql + */ + public void setSqlTable ( javax.swing.JTable table, String sql ) { + try { + DefaultTableModel modelo_tabela = ( DefaultTableModel ) table.getModel (); + Statement s = conexao.createStatement (); + ResultSet rs = s.executeQuery ( sql ); + ResultSetMetaData rsmd = rs.getMetaData (); + int quantCOLUNAS = rsmd.getColumnCount (); + List nomeCOLUNAS = new List (); + int contador = 0; + while ( quantCOLUNAS > contador ) { + contador ++; + nomeCOLUNAS.add ( rsmd.getColumnLabel ( contador ) ); + } + modelo_tabela.setColumnCount ( 0 ); + contador = 0; + while ( quantCOLUNAS > contador ) { + modelo_tabela.addColumn ( nomeCOLUNAS.get ( contador ) ); + contador ++; + } + modelo_tabela.setRowCount ( 0 ); + List linha = new List (); + while ( rs.next () ) { + linha.clear (); + contador = 0; + while ( quantCOLUNAS > contador ) { + linha.add ( rs.getString ( nomeCOLUNAS.get ( contador ).toString () ) ); + contador ++; + } + modelo_tabela.addRow ( linha.toArray () ); + } + table.setModel ( modelo_tabela ); + rs.close (); + s.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + } + + /** + * Mesma coisa que o setSQLtabela porem usa como titulo o arraylist + * + * @param table tabela + * @param sql sql + * @param lista titulos + */ + public void setSqlTable ( javax.swing.JTable table, String sql, String[] lista ) { + try { + DefaultTableModel modelo_tabela = ( DefaultTableModel ) table.getModel (); + Statement s = conexao.createStatement (); + ResultSet rs = s.executeQuery ( sql ); + ResultSetMetaData rsmd = rs.getMetaData (); + int quantCOLUNAS = rsmd.getColumnCount (); + List nomeCOLUNAS = new List (); + int contador = 0; + while ( quantCOLUNAS > contador ) { + contador ++; + nomeCOLUNAS.add ( rsmd.getColumnLabel ( contador ) ); + } + modelo_tabela.setColumnCount ( 0 ); + contador = 0; + while ( quantCOLUNAS > contador ) { + //contador++; + modelo_tabela.addColumn ( lista[ contador ] ); + contador ++; + } + modelo_tabela.setRowCount ( 0 ); + List linha = new List (); + while ( rs.next () ) { + linha.clear (); + contador = 0; + while ( quantCOLUNAS > contador ) { + linha.add ( rs.getString ( nomeCOLUNAS.get ( contador ).toString () ) ); + contador ++; + } + modelo_tabela.addRow ( linha.toArray () ); + } + table.setModel ( modelo_tabela ); + rs.close (); + s.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + } + + /** + * Mesma coisa que o setSQLtabela2 porém usa um resultset ao invez de um + * texto com sql + * + * @param table tabela + * @param r resultado já filtrado + * @param lista campos da tabela + */ + public static void setSqlTable ( javax.swing.JTable table, ResultSet r, String[] lista ) { + try { + DefaultTableModel modelo_tabela = ( DefaultTableModel ) table.getModel (); + ResultSet rs = r; + ResultSetMetaData rsmd = rs.getMetaData (); + int quantCOLUNAS = rsmd.getColumnCount (); + List nomeCOLUNAS = new List (); + int contador = 0; + while ( quantCOLUNAS > contador ) { + contador ++; + nomeCOLUNAS.add ( rsmd.getColumnLabel ( contador ) ); + } + modelo_tabela.setColumnCount ( 0 ); + contador = 0; + while ( quantCOLUNAS > contador ) { + //contador++; Opa :P + modelo_tabela.addColumn ( lista[ contador ] ); + contador ++; + } + modelo_tabela.setRowCount ( 0 ); + List linha = new List (); + while ( rs.next () ) { + linha.clear (); + contador = 0; + while ( quantCOLUNAS > contador ) { + linha.add ( rs.getString ( nomeCOLUNAS.get ( contador ).toString () ) ); + contador ++; + } + modelo_tabela.addRow ( linha.toArray () ); + } + table.setModel ( modelo_tabela ); + rs.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + } + + /** + * Atribui a um combo o valor de um campo do select + * + * @param combo javax.jComboBox + * @param sql String sql + */ + public void setSqlCombo ( javax.swing.JComboBox combo, String sql ) { + try { + DefaultComboBoxModel modelo_combo = ( DefaultComboBoxModel ) combo.getModel (); + modelo_combo.removeAllElements (); + Statement s = conexao.createStatement (); + ResultSet rs = s.executeQuery ( sql ); + while ( rs.next () ) { + modelo_combo.addElement ( rs.getString ( 1 ) ); + } + combo.setModel ( modelo_combo ); + rs.close (); + s.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + } + + /** + * Executa uma instrução SQL de forma direta e insegura + * + * @param sql String sql + */ + public boolean exec ( String sql ) { + boolean retorno = false; + try { + Statement s = conexao.createStatement (); + retorno = s.execute ( sql ); + s.close (); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return retorno; + } + + public boolean Texec ( String sql ) throws SQLException { + boolean retorno = false; + Statement s = conexao.createStatement (); + retorno = s.execute ( sql ); + s.close (); + return retorno; + } + + public boolean exec ( String sql, String[] parametros ) { + return prepareCommand ( sql, parametros ); + } + + /** + * Executa uma instrução SQL retornando um Objeto resultSet para seu uso. + * + * @param sql + * @return Objeto resultSet para seu uso. + */ + public ResultSet ret ( String sql ) { + ResultSet r = null; + try { + Statement s = conexao.createStatement (); + r = s.executeQuery ( sql ); +// s.close(); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return r; + } + + /** + * Identico ao executa porém de forma segura + * + * @param sql + * @param argumentos Uma lista que substituirá de forma segura os =? do SQL + * + */ + public boolean prepareCommand ( String sql, String[] argumentos ) { + boolean retorno = true; + try { + PreparedStatement ps = conexao.prepareStatement ( sql ); + for ( int contador = 0; contador < argumentos.length; contador ++ ) { + int ips = contador + 1; + ps.setString ( ips, argumentos[ contador ] ); + } + if ( tipo == Tipos.POSTGRESQL ) { + retorno = exec ( ps.toString () ); + } else { + retorno = ps.execute (); + } + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return retorno; + } + + /** + * Mistura de preparaexecuta com retorna + * + * @param sql + * @param argumentos + * @return um objeto ResultSet + */ + public ResultSet prepareResultSet ( String sql, String[] argumentos ) { + ResultSet r = null; + try { + PreparedStatement ps = conexao.prepareStatement ( sql ); + for ( int contador = 0; contador < argumentos.length; contador ++ ) { + int ips = contador + 1; + ps.setObject ( ips, argumentos[ contador ] ); + } + if ( tipo == Tipos.POSTGRESQL ) { //bancos que o driver usar server size validation + r = ret ( ps.toString () ); + } else { + r = ps.executeQuery (); + } + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return r; + } + + public List> get ( String sql, String[] argumentos ) { + return get ( prepareResultSet ( sql, argumentos ) ); + } + + public List> get ( String sql ) { + return get ( ret ( sql ) ); + } + + public static List> get ( ResultSet r ) { + List> retorno = new List> (); + try { + ResultSetMetaData re = null; + String nameColumn = ""; + String valueColumn = ""; + while ( r.next () ) { + re = r.getMetaData (); + Map m = new Map<> (); + int countColumn = re.getColumnCount (); + for ( int i = 1; i <= countColumn; i ++ ) { + nameColumn = re.getColumnLabel ( i ); + valueColumn = r.getString ( i ); + m.put ( nameColumn, valueColumn ); + } + retorno.add ( m ); + } + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return retorno; + } + + public List> Tget ( String sql, String[] argumentos ) throws Exception { + return get ( prepareResultSet ( sql, argumentos ) ); + } + + public List> Tget ( String sql ) throws Exception { + return get ( ret ( sql ) ); + } + + public static List> Tget ( ResultSet r ) throws Exception { + List> retorno = new List> (); + ResultSetMetaData re = null; + String nameColumn = ""; + String valueColumn = ""; + while ( r.next () ) { + re = r.getMetaData (); + Map m = new Map<> (); + int countColumn = re.getColumnCount (); + for ( int i = 1; i <= countColumn; i ++ ) { + nameColumn = re.getColumnLabel ( i ); + valueColumn = r.getString ( i ); + m.put ( nameColumn, valueColumn ); + } + retorno.add ( m ); + } + return retorno; + } + + public static String createTable ( Class c ) { + String sql = "create table " + c.getSimpleName () + " ("; + Field[] declaredFields = c.getDeclaredFields (); + for ( Field declaredField : declaredFields ) { + String name = declaredField.getName (); + String typeName = declaredField.getType ().getName (); + // + if ( typeName.equals ( "java.lang.String" ) ) { + typeName = "TEXT"; + } else if ( typeName.equals ( "java.lang.Integer" ) ) { + typeName = "INTEGER"; + } else if ( typeName.equals ( "java.lang.Boolean" ) ) { + typeName = "TEXT"; + } else if ( typeName.equals ( "java.lang.Float" ) ) { + if ( tipo == Tipos.SQLITE ) { + typeName = "NUMERIC"; + } else { + typeName = "FLOAT"; + } + } else if ( typeName.equals ( "jpkj.Calendar" ) ) { + typeName = "TIMESTAMP"; + } else { + typeName = "INTEGER"; + } + // + String adds = ""; + Annotation[] annotations = declaredField.getAnnotations (); + for ( Annotation annotation : annotations ) { + String annotationName = annotation.annotationType ().getName (); + // + if ( annotationName.equals ( "jpkj.annotation.Type" ) ) { + jpkj.annotation.Type forcedType = ( jpkj.annotation.Type ) annotation; + typeName = forcedType.value (); + } else if ( annotationName.equals ( "jpkj.annotation.Id" ) ) { + jpkj.annotation.Id id = ( jpkj.annotation.Id ) annotation; + if ( id.isPk () ) { + adds += " PRIMARY KEY "; + } + if ( id.isAI () ) { + if ( tipo == Tipos.MYSQL ) { + adds += " AUTO_INCREMENT "; + } else { + adds += " AUTOINCREMENT "; + } + } + } else if ( annotationName.equals ( "jpkj.annotation.Default" ) ) { + jpkj.annotation.Default defaulte = ( jpkj.annotation.Default ) annotation; + adds += "DEFAULT " + defaulte.value () + " "; + } + // + } + sql += name + " " + typeName + " " + adds + " " + ","; + } + sql = sql.substring ( 0, sql.length () - 1 ); + sql += ")"; + return sql; + } + + /** + * Retorna uma lista com uma lista que tem as linhas da tabela. + * + * @param r ResultSet NÂO VAI ACHAR QUE È STRING SQL ANIMAL + * @return uma lista com uma lista que tem as linhas da tabela. + */ + public static List> getArray ( ResultSet r ) { + List> l = new List> ();//tchau jdk6 só que não + try { + ResultSetMetaData re = r.getMetaData (); + while ( r.next () ) { + List li = new List (); + for ( int i = 1; i <= re.getColumnCount (); i ++ ) { + li.add ( r.getString ( i ) ); + } + l.add ( li ); + } + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return l; + } + + /** + * Retorna uma lista com uma lista que tem as linhas da tabela. + * + * @param sql instrução SQL + * @return uma lista com uma lista que tem as linhas da tabela. + */ + public List> getArray ( String sql ) { + return getArray ( ret ( sql ) ); + } + + /** + * Retorna o texto com a instrução sql + * + * @param tabela nome da tabela + * @param campos campos separados por virgula + * @param nomes nome dos campos + * @param valores valores dos campos + * @return texto com a instrução sql + */ + public static String Select ( String tabela, String campos, Object[] nomes, Object[] valores ) { + String sql = "select " + campos + " from " + tabela + " where "; + for ( int i = 0; i < nomes.length; i ++ ) { + String valor = valores[ i ].toString (); + String nome = nomes[ i ].toString (); + if ( i < nomes.length - 1 ) { + sql += nome + "'" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "'" + " and "; + } else { + sql += nome + "'" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "'"; + } + } + return sql; + } + + /** + * Retorna o texto com a instrução sql + * + * @param tabela nome da tabela + * @param where condicao + * @return texto com a instrução sql + */ + public static String Delete ( String tabela, String where ) { + String sql = "delete from " + tabela + " where " + where; + return sql; + } + + public static String Update ( String tabela, Map mapa, String where ) { + List values = new List (); + for ( Object key : mapa.getKeys () ) { + values.add ( mapa.toString ( key ) ); + } + return Update ( tabela, mapa.getKeys ().toArray (), values.toStringArray (), where ); + } + + /** + * Retorna um texto de um update na tabela. + * + * @param tabela nome da tabela + * @param nomes nome dos campos + * @param valores valores dos campos + * @param where condição de filtro para a atualização + * @return Texto com a instrução sql + */ + public static String Update ( String tabela, Object[] nomes, Object[] valores, String where ) { + String sql = "update " + tabela + " set "; + for ( int i = 0; i < nomes.length; i ++ ) { + String valor = valores[ i ].toString (); + String nome = nomes[ i ].toString (); + if ( i < nomes.length - 1 ) { + sql += nome + " = '" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "',"; + } else { + sql += nome + " = '" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "'"; + } + } + sql += "where " + where; + return sql; + } + + public static String Insert ( String tabela, Map mapa ) { + List values = new List (); + for ( Object key : mapa.getKeys () ) { + values.add ( mapa.toString ( key ) ); + } + return Insert ( tabela, mapa.getKeys ().toArray (), values.toStringArray () ); + } + + /** + * Retorna o texto de um insert na tabela + * + * @param tabela nome da tabela + * @param nomes nomes dos campos + * @param valores valores dos campos + * @return Texto com a instrução sql + */ + public static String Insert ( String tabela, Object[] nomes, Object[] valores ) { + String sql = "insert into " + tabela + " ("; + for ( int i = 0; i < nomes.length; i ++ ) { + String valor = valores[ i ].toString (); + String nome = nomes[ i ].toString (); + if ( i < nomes.length - 1 ) { + sql += nome + ","; + } else { + sql += nome; + } + } + sql += ") values("; + for ( int i = 0; i < nomes.length; i ++ ) { + String valor = valores[ i ].toString (); + String nome = nomes[ i ].toString (); + if ( i < nomes.length - 1 ) { + sql += "'" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "',";//para não dizer que não falei das flores + } else { + sql += "'" + valor.replaceAll ( Pattern.quote ( "'" ), "" ) + "'"; + } + } + return sql + ")"; + } + + /** + * Lê um arquivo e retorna a representação hexadecimal que é usado na + * armazenagem dos tipos blobs + * + * @param file Arquivo a ser lido + * @return Representação em hexadecimal + */ + public static String fileToSQL ( File file ) { + return Hex.encodeHexString ( UtilFile.loadBIN ( file ) ); + } + + /** + * Transforma um hexadecima em um array de bytes para gravar com a classe + * UtilFile exemplo UtilFile.writeBIN("a.jpg", Db.sQLToFile("aa a1 00")); + * + * @param input + * @return Array de bytes + */ + public static byte[] sQLToFile ( String input ) { + byte[] retorno = null; + try { + retorno = Hex.decodeHex ( input.toCharArray () ); + } catch ( Exception e ) { + Log.out ( Util.exeptionToString ( e ) ); + } + return retorno; + } + + public boolean exists ( String table, String where ) { + return get ( "select id from " + table + " where " + where ).size () > 0; + } +} diff --git a/src/jpkj/Entry.java b/src/jpkj/Entry.java new file mode 100644 index 0000000..c5aeb01 --- /dev/null +++ b/src/jpkj/Entry.java @@ -0,0 +1,80 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +/** + * + * @author felipe + */ +public class Entry { + + /** + * Abre uma janela para entrada de texto. + * + * @param titulo titulo que será aparecido + * @return + */ + public static String show(String titulo) { + return javax.swing.JOptionPane.showInputDialog(titulo); + } + + public static int showInt(String titulo) { + Integer retorno = 0; + boolean ok = true; + do { + String tmp = javax.swing.JOptionPane.showInputDialog(titulo).trim(); + try { + retorno = Integer.parseInt(tmp); + ok = true; + } catch (Exception e) { + ok = false; + } finally { + } + } while (!ok); + return retorno; + } + + public static double showDouble(String titulo) { + Double retorno = 0.0; + boolean ok = true; + do { + String tmp = javax.swing.JOptionPane.showInputDialog(titulo).trim(); + try { + retorno = Double.parseDouble(tmp); + ok = true; + } catch (Exception e) { + ok = false; + } finally { + } + } while (!ok); + return retorno; + } + + public static float showFloat(String titulo) { + Float retorno = 0.0f; + boolean ok = true; + do { + String tmp = javax.swing.JOptionPane.showInputDialog(titulo).trim(); + try { + retorno = Float.parseFloat(tmp); + ok = true; + } catch (Exception e) { + ok = false; + } finally { + } + } while (!ok); + return retorno; + } + + public static String button(String titulo, String[] ops) { + return BTN(titulo, ops); + } + + public static String BTN(String titulo, String[] ops) { + String[] op = ops; + Object ret = javax.swing.JOptionPane.showOptionDialog(null, titulo, "", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.INFORMATION_MESSAGE, null, op, op[0]); + return op[Integer.valueOf(ret.toString())]; + } +} diff --git a/src/jpkj/Ireport.java b/src/jpkj/Ireport.java new file mode 100644 index 0000000..49b5a7e --- /dev/null +++ b/src/jpkj/Ireport.java @@ -0,0 +1,38 @@ +package jpkj; + +import java.io.File; +import java.sql.Connection; +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.Map; +import javax.swing.JFrame; +import net.sf.jasperreports.engine.JRResultSetDataSource; +import net.sf.jasperreports.engine.JasperPrint; + +public class Ireport { + + public static void show(File arquivo, ResultSet rs) { + try { + JRResultSetDataSource jds = new JRResultSetDataSource(rs); + JasperPrint rel = net.sf.jasperreports.engine.JasperFillManager.fillReport(arquivo.getPath(), null, jds); + JFrame frame = new JFrame(); + frame.getContentPane().add(new net.sf.jasperreports.view.JasperViewer(rel).getContentPane()); + frame.setExtendedState(JFrame.MAXIMIZED_BOTH); + frame.setVisible(true); + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } + } + + public static void show(File arquivo, HashMap p,Connection c) { + try { + JasperPrint rel = net.sf.jasperreports.engine.JasperFillManager.fillReport(arquivo.getPath(), p, c); + JFrame frame = new JFrame(); + frame.getContentPane().add(new net.sf.jasperreports.view.JasperViewer(rel).getContentPane()); + frame.setExtendedState(JFrame.MAXIMIZED_BOTH); + frame.setVisible(true); + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } + } +} diff --git a/src/jpkj/List.java b/src/jpkj/List.java new file mode 100644 index 0000000..52e24f0 --- /dev/null +++ b/src/jpkj/List.java @@ -0,0 +1,99 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Locale; + +/** + * + * @author Administrator + * @param + */ +public class List extends ArrayList { + + public String[] toStringArray() { + String[] r = new String[this.size()]; + for (int i = 0; i < this.size(); i++) { + r[i] = this.get(i).toString(); + } + return r; + } + + public String toString(int key) { + return this.get(key).toString(); + } + + public Integer[] toIntegerArray() { + Integer[] r = new Integer[this.size()]; + for (int i = 0; i < this.size(); i++) { + r[i] = Integer.parseInt(this.get(i).toString()); + } + return r; + } + + public Integer toInteger(int key) { + return Integer.parseInt(this.toString(key)); + } + + public Float[] toFloatArray() { + Float[] r = new Float[this.size()]; + for (int i = 0; i < this.size(); i++) { + r[i] = Float.parseFloat(this.get(i).toString()); + } + return r; + } + + public Float toFloat(int key) { + return Float.parseFloat(this.toString(key)); + } + + public Double[] toDoubleArray() { + Double[] r = new Double[this.size()]; + for (int i = 0; i < this.size(); i++) { + r[i] = Double.parseDouble(this.get(i).toString()); + } + return r; + } + + public Double toDouble(int key) { + return Double.parseDouble(this.toString(key)); + } + + public String toCurrency(int key, Locale local) { + String retorno = ""; + NumberFormat.getCurrencyInstance(local); + retorno = NumberFormat.getCurrencyInstance().format(this.toString(key)); + return retorno; + } + + public String toCurrency(int key) { + return this.toCurrency(key, Locale.getDefault()); + } + + public Calendar[] toCalendarArray() { + Calendar[] r = new Calendar[this.size()]; + for (int i = 0; i < this.size(); i++) { + r[i] = new Calendar(this.get(i).toString()); + } + return r; + } + + public Calendar toCalendar(int key) { + return (new Calendar(this.toString(key))); + } + + @Override + public E get(int i) { + if (i > this.size()) { + return null; + } else { + return super.get(i); + } + } + +} diff --git a/src/jpkj/Log.java b/src/jpkj/Log.java new file mode 100644 index 0000000..f2c486b --- /dev/null +++ b/src/jpkj/Log.java @@ -0,0 +1,21 @@ +package jpkj; + +public class Log { + + public static String cout = "cmd"; + public static String in() { + return Console.readLine(); + } + + public static void out(Object text) { + if (Log.cout.equals("cmd")) { + Console.writeLine(text); + } else { + if (UtilFile.exists(Log.cout)) { + text = UtilFile.load(Log.cout) + "\n" + text; + } + text += "|"+new Calendar().format(null); + UtilFile.write(Log.cout, text.toString()); + } + } +} diff --git a/src/jpkj/Map.java b/src/jpkj/Map.java new file mode 100644 index 0000000..2b60b03 --- /dev/null +++ b/src/jpkj/Map.java @@ -0,0 +1,63 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import java.text.NumberFormat; +import java.util.HashMap; +import java.util.Locale; + +/** + * + * @author Administrator + * @param + * @param + */ +public class Map extends HashMap { + + public List getKeys() { + List r = new List(); + for (Object object : this.keySet()) { + r.add(object); + } + return r; + } + + public String toString(Object key) { + if (this.get(key) == null) { + return ""; + } else { + return this.get(key).toString(); + } + } + + public Integer toInteger(Object key) { + return Integer.parseInt(this.toString(key)); + } + + public Float toFloat(Object key) { + return Float.parseFloat(this.toString(key)); + } + + public Double toDouble(Object key) { + return Double.parseDouble(this.toString(key)); + } + + public String toCurrency(Object key, Locale local) { + String retorno = ""; + NumberFormat.getCurrencyInstance(local); + retorno = NumberFormat.getCurrencyInstance().format(this.toString(key)); + return retorno; + } + + public String toCurrency(Object key) { + return this.toCurrency(key, Locale.getDefault()); + } + + public Calendar toCalendar(Object key) { + return (new Calendar(this.toString(key))); + } + +} diff --git a/src/jpkj/MaskDate.java b/src/jpkj/MaskDate.java new file mode 100644 index 0000000..4fee8b7 --- /dev/null +++ b/src/jpkj/MaskDate.java @@ -0,0 +1,39 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; +/** + * + * @author felipe + */ + +public class MaskDate extends PlainDocument { + + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + String texto = getText(0, getLength()); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (!Character.isDigit(c)) { + return; + } + } + super.remove(0, getLength()); + StringBuffer s = new StringBuffer(texto + str); + if (offs == 2) { + s.insert(offs, "/"); + } + if (offs == 5) { + s.insert(offs, "/"); + } + if (offs > 8) { + super.insertString(0, s.toString().substring(0, 10), a); + } else { + super.insertString(0, s.toString(), a); + } + } +} diff --git a/src/jpkj/MaskHour.java b/src/jpkj/MaskHour.java new file mode 100644 index 0000000..a330a7c --- /dev/null +++ b/src/jpkj/MaskHour.java @@ -0,0 +1,40 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; + +/** + * + * @author felipe + */ +public class MaskHour extends PlainDocument { + + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + String texto = getText(0, getLength()); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (!Character.isDigit(c)) { + return; + } + } + super.remove(0, getLength()); + StringBuffer s = new StringBuffer(texto + str); + if (offs == 2) { + s.insert(offs, ":"); + } + if (offs == 5) { + s.insert(offs, ":"); + } + if (offs > 6) { + super.insertString(0, s.toString().substring(0, 8), a); + } else { + super.insertString(0, s.toString(), a); + } + } +} \ No newline at end of file diff --git a/src/jpkj/MaskMoney.java b/src/jpkj/MaskMoney.java new file mode 100644 index 0000000..7cfa965 --- /dev/null +++ b/src/jpkj/MaskMoney.java @@ -0,0 +1,66 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; + +/** + * + * @author felipe + */ + +public class MaskMoney extends PlainDocument { + + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + String texto = getText(0, getLength()); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (!Character.isDigit(c)) { + return; + } + } + super.remove(0, getLength()); + texto = texto.replace(".", "").replace(",", ""); + StringBuffer s = new StringBuffer(texto + str); + + if (s.length() > 0 && s.charAt(0) == '0') { + s.deleteCharAt(0); + } + + if (s.length() < 3) { + if (s.length() < 1) { + s.insert(0, "000"); + } else if (s.length() < 2) { + s.insert(0, "00"); + } else { + s.insert(0, "0"); + } + } + + s.insert(s.length() - 2, "."); + + if (s.length() > 6) { +// s.insert(s.length() - 6, "."); + } + + if (s.length() > 10) { +// s.insert(s.length() - 10, "."); + } + + super.insertString(0, s.toString(), a); + } + + public void remove(int offset, int length) throws BadLocationException { + super.remove(offset, length); + String texto = getText(0, getLength()); + texto = texto.replace(",", ""); + texto = texto.replace(".", ""); + super.remove(0, getLength()); + insertString(0, texto, null); + } +} diff --git a/src/jpkj/MaskNumber.java b/src/jpkj/MaskNumber.java new file mode 100644 index 0000000..5ec5100 --- /dev/null +++ b/src/jpkj/MaskNumber.java @@ -0,0 +1,27 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj; + +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; + +/** + * + * @author felipe + */ + +public class MaskNumber extends PlainDocument { + + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + try { + int v = Integer.parseInt(str.substring(0, 1)); + } catch (Exception e) { + return; + } + super.insertString(offs, str, a); //To change body of generated methods, choose Tools | Templates. + } +} \ No newline at end of file diff --git a/src/jpkj/Msg.java b/src/jpkj/Msg.java new file mode 100644 index 0000000..f1e735a --- /dev/null +++ b/src/jpkj/Msg.java @@ -0,0 +1,19 @@ + +package jpkj; + +public class Msg { +/** + * Mostra uma mensagem :) + * @param mensagem + */ + public Msg(String mensagem) { + Swing.msg(mensagem); + } +/** + * Mostra uma mensagem :) + * @param mensagem + */ + public static void show(String mensagem) { + Swing.msg(mensagem); + } +} diff --git a/src/jpkj/P2P.java b/src/jpkj/P2P.java new file mode 100644 index 0000000..07e0d12 --- /dev/null +++ b/src/jpkj/P2P.java @@ -0,0 +1,99 @@ +package jpkj; + +import java.net.*; +import java.io.*; +import org.apache.commons.io.IOUtils; + +public class P2P { + + int socketsAtivos = 0; + ServerSocket ss = null; + boolean vida = true; + + public String execute(String conteudo, String origem) { + return ""; + } + + public P2P(final int porta) { + new Thread() { + Socket s = null; + ServerSocket ss = null; + + @Override + public void run() { + try { + ss = new ServerSocket(porta); + } catch (IOException iOException) { + Log.out(Util.exeptionToString(iOException)); + } + s = null; + // + while (vida) { + try { + if (!ss.isClosed()) { + ss.close(); + } + ss = new ServerSocket(porta); + s = ss.accept(); + new Thread() { + @Override + public void run() { + try { + if (s.isClosed() && !s.isConnected()) { + return; + } + InputStream input = s.getInputStream(); + OutputStream output = s.getOutputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(input)); + String total = ""; + String header = ""; + do { + total += br.readLine() + "\r\n"; + } while (br.ready()); + PrintWriter pw = new PrintWriter(output, true); + + String resposta = execute(total.trim(), s.getInetAddress().getHostAddress()); + pw.write(resposta.trim()); + pw.flush(); + s.close(); + Thread.sleep(5); + } catch (Exception iOException) { + Log.out(Util.exeptionToString(iOException)); + } finally { + } + } + }.start(); + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } finally { + } + } + }//thread + }.start();//Thread + } + + public static String send(String host, int porta, String conteudo) { + String retorno = "Sem resposta"; + try { + conteudo = "\r\n" + conteudo; + Socket conexao = new Socket(host, porta); + PrintStream ps = new PrintStream(conexao.getOutputStream()); + ps.println(conteudo); + BufferedReader br = new BufferedReader(new InputStreamReader(conexao.getInputStream())); + String linha = "", total = ""; + while ((linha = br.readLine()) != null) { + total += linha; + } + br.close(); + retorno = total; + ps.flush(); + ps.close(); + conexao.close(); + } catch (ConnectException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return retorno; + } +} diff --git a/src/jpkj/Swing.java b/src/jpkj/Swing.java new file mode 100644 index 0000000..ef31ee6 --- /dev/null +++ b/src/jpkj/Swing.java @@ -0,0 +1,260 @@ +package jpkj; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.*; +import java.beans.PropertyChangeListener; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Vector; +import javax.swing.table.*; +import javax.swing.*; +import javax.swing.event.CellEditorListener; +import javax.swing.text.MaskFormatter; + +/** + * + * @author felipe + */ +public class Swing { + + public static void clearTable(JTable table) { + DefaultTableModel modelo_tabela = (DefaultTableModel) table.getModel(); + modelo_tabela.setRowCount(0); + modelo_tabela.setColumnCount(0); + + table.setModel(modelo_tabela); + } + + public static void setListCombo(JComboBox combo, String[] dados) { + DefaultComboBoxModel modelo = (DefaultComboBoxModel) combo.getModel(); + modelo.removeAllElements(); + for (String string : dados) { + modelo.addElement(string); + } + combo.setModel(modelo); + } + + public static void lookTable(JTable tabela) { + DefaultTableModel modelo = (DefaultTableModel) tabela.getModel(); + tabela.getTableHeader().setReorderingAllowed(false); + modelo = new DefaultTableModel() { + @Override + public boolean isCellEditable(int row, int column) { + return false; + } + }; + tabela.setModel(modelo); + } + + public static String columnType_check = "checkbox"; + public static String columnType_combo = "combobox"; + public static String columnType_text = "textfield"; + // http://developer.classpath.org/doc/javax/swing/table/DefaultTableCellRenderer-source.html + + public static void changeColumnType(final JTable tabela, int indiceColuna, final String columnType) { + tabela.getColumnModel().getColumn(indiceColuna).setCellRenderer(new DefaultTableCellRenderer() { + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + Component retorno = null; + if (columnType.equalsIgnoreCase(Swing.columnType_check)) { + retorno = (JCheckBox) (table.getValueAt(row, column)); + } else if (columnType.equalsIgnoreCase(Swing.columnType_combo)) { + retorno = (JComboBox) table.getValueAt(row, column); + } else { + retorno = (JTextField) table.getValueAt(row, column); + } + return retorno; + } + }); + if (columnType.equalsIgnoreCase(Swing.columnType_check)) { + tabela.getColumnModel().getColumn(indiceColuna).setCellEditor(new DefaultCellEditor(new JCheckBox()) { + @Override + public Object getCellEditorValue() { + JCheckBox ele = (JCheckBox) tabela.getValueAt(tabela.getSelectedRow(), tabela.getSelectedColumn()); + ele.setSelected(!ele.isSelected()); + return ele; + } + }); + } else if (columnType.equalsIgnoreCase(Swing.columnType_combo)) { + tabela.getColumnModel().getColumn(indiceColuna).setCellEditor(new DefaultCellEditor(new JComboBox()) { + public JComponent getEditorComponent() { + JComboBox ele = (JComboBox) tabela.getValueAt(tabela.getSelectedRow(), tabela.getSelectedColumn()); + this.editorComponent = ele; + return ele; + } + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + JComboBox ele = (JComboBox) table.getValueAt(row, column); + this.editorComponent = ele; + return ele; + } + + @Override + public Object getCellEditorValue() { + JComboBox ele = (JComboBox) tabela.getValueAt(tabela.getSelectedRow(), tabela.getSelectedColumn()); + this.editorComponent = ele; + return ele; + } + }); + } else { + tabela.getColumnModel().getColumn(indiceColuna).setCellEditor(new DefaultCellEditor(new JTextField()) { + public JComponent getEditorComponent() { + JTextField ele = (JTextField) tabela.getValueAt(tabela.getSelectedRow(), tabela.getSelectedColumn()); + this.editorComponent = ele; + return ele; + } + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + JTextField ele = (JTextField) table.getValueAt(row, column); + this.editorComponent = ele; + return ele; + } + + @Override + public Object getCellEditorValue() { + JTextField ele = (JTextField) tabela.getValueAt(tabela.getSelectedRow(), tabela.getSelectedColumn()); + this.editorComponent = ele; + return ele; + } + }); + } + } + + public static KeyListener autoComplete(final JTextField campo, final String[] itens) { + campo.setText(""); + itens[itens.length] = ""; + KeyListener retorno = new KeyListener() { + String jaDigitado = ""; + + @Override + public void keyTyped(KeyEvent ke) { + } + + @Override + public void keyPressed(KeyEvent ke) { + } + + @Override + public void keyReleased(KeyEvent ke) { + try { + campo.setText(campo.getText().substring(0, campo.getText().length() - 1)); + } catch (Exception e) { + } finally { + } + if (ke.getKeyCode() == 8 && jaDigitado.length() > 0) {//apagar + jaDigitado = jaDigitado.substring(0, jaDigitado.length() - 1);//remover o ultimo + } + if (ke.getKeyCode() != 8 && ke.getKeyCode() != 16) { + jaDigitado += new String(("" + ke.getKeyChar()));//Tinha um motivo não lembro qual + } + boolean passou = false; + String digitado = campo.getText();//Sei lá mil tretas .. + for (String string : itens) { + if (string.startsWith(jaDigitado)) { + passou = true; + campo.setText(string); + campo.setCaretPosition(jaDigitado.length()); + campo.setSelectionStart(jaDigitado.length()); + campo.setSelectionEnd(string.length()); + break; + } + } + if (!passou) { + jaDigitado = jaDigitado.substring(0, jaDigitado.length() - 1);//remover o ultimo + } + } + }; + campo.addKeyListener(retorno); + return retorno; + } + + public static void dontChangeFocusLost(JFormattedTextField field) { + field.setFocusLostBehavior(JFormattedTextField.PERSIST); + } + + public static void msg(String menssagem) { + JOptionPane.showMessageDialog(null, menssagem); + } + + public static void addLineTable(javax.swing.JTable tabela, java.util.ArrayList linha) { + DefaultTableModel modelo_tabela = (DefaultTableModel) tabela.getModel(); + modelo_tabela.addRow(linha.toArray()); + tabela.setModel(modelo_tabela); + } + + public static void addLineTable(javax.swing.JTable tabela, String linha[]) { + DefaultTableModel modelo_tabela = (DefaultTableModel) tabela.getModel(); + modelo_tabela.addRow(linha); + tabela.setModel(modelo_tabela); + } + + public static void addLineTable(javax.swing.JTable tabela, Object linha[]) { + DefaultTableModel modelo_tabela = (DefaultTableModel) tabela.getModel(); + modelo_tabela.addRow(linha); + tabela.setModel(modelo_tabela); + } + + public static void addColumnTable(javax.swing.JTable tabela, String coluna) { + DefaultTableModel modelo_tabela = (DefaultTableModel) tabela.getModel(); + modelo_tabela.addColumn(coluna); + tabela.setModel(modelo_tabela); + } + + public static DefaultTableModel getModelTable(javax.swing.JTable tabela) { + return (DefaultTableModel) tabela.getModel(); + } + + public static void setModelTable(javax.swing.JTable tabela, javax.swing.table.DefaultTableModel modelo_tabela) { + tabela.setModel(modelo_tabela); + } + + /** + * Pega o valor da coluna com a linha selecionada. + * + * @param table JTable + * @param coluna Coluna que começa com 0 + * @return String com o valor + */ + public static String getSelect(JTable table, int coluna) { + if (table.getRowCount() < 1) { + return ""; + } + return table.getValueAt(table.getSelectedRow(), coluna).toString(); + } + + /** + * Adiciona automaticamente a quantidade de 0 que for preciso. + * + * @param f O elemento a ser formatado. + */ + public static void addZeros(final JFormattedTextField f) { + f.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent fe) { + return; + } + + @Override + public void focusLost(FocusEvent fe) { + String zeros = ""; + MaskFormatter m = (MaskFormatter) f.getFormatter(); + int tamanho = m.getMask().length(); + String t = f.getText().trim(); + /* + * for (int i = 0; i < t.length(); i++) { if (t.charAt(i) == + * "0".charAt(0)) { t = t.substring(i, t.length() - i); } else { + * break; } } + * + */ + for (int i = t.length(); i < tamanho; i++) { + zeros += "0"; + } + f.setText(zeros + t); + } + }); + } +} diff --git a/src/jpkj/Util.java b/src/jpkj/Util.java new file mode 100644 index 0000000..bbb3a30 --- /dev/null +++ b/src/jpkj/Util.java @@ -0,0 +1,133 @@ +package jpkj; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.text.NumberFormat; +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.LookAndFeel; +import javax.swing.UIManager; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.StringUtils; + +public class Util { + + public static String formatNumber(double numero) { + String retorno = ""; + retorno = NumberFormat.getCurrencyInstance().format(numero); + return retorno; + } + + public static String exeptionToString(Throwable e) { + StringBuilder sb = new StringBuilder(); + sb.append(e.getMessage()); + sb.append("\n"); + sb.append("message : "+e.getMessage()); + sb.append("localized : "+e.getLocalizedMessage()); + for (StackTraceElement element : e.getStackTrace()) { + sb.append(element.toString()); + sb.append("\n"); + } + return sb.toString(); + } + + public static String base64Decode(String s) { + return StringUtils.newStringUtf8(Base64.decodeBase64(s)); + } + + public static String base64Encode(String s) { + return Base64.encodeBase64String(StringUtils.getBytesUtf8(s)); + } + + public static String cmd(String comando) { + String retorno = ""; + try { + Process exec = Runtime.getRuntime().exec(comando); + BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream())); + String linha = "", total = ""; + while ((linha = br.readLine()) != null) { + total += linha + "\r\n"; + } + retorno = new String(total.getBytes("UTF-8")); + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } + return retorno; + } + + public static void showJFrame(JFrame janela, String title) { + showJFrame(janela, title, false, null); + } + + public static void showJFrame(JFrame janela, String title, File icon) { + showJFrame(janela, title, false, icon); + } + + public static void showJFrame(JFrame janela, String title, boolean close) { + showJFrame(janela, title, close, null); + } + + public static void showJFrame(JFrame janela, String title, boolean close, File icon) { + janela.setTitle(title); + if (!close) { + janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } else { + janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + if (icon != null) { + ImageIcon imageIcon = new ImageIcon(icon.getAbsolutePath()); + janela.setIconImage(imageIcon.getImage()); + } + janela.setLocationRelativeTo(null); + janela.setVisible(true); + } + public static int MAC = 0; + public static int WINDOWS = 1; + public static int WINDOWS_CLASSIC = 2; + public static int GTK = 3; + public static int JAVA = 4; + public static int NIMBUS = 5; + public static int SISTEMA = 6; + + public static void changeTheme(LookAndFeel laf) { + try { + UIManager.setLookAndFeel(laf); + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } + } + public static void changeTheme(int tema) { + try { + switch (tema) { + case 0: + UIManager.setLookAndFeel("ch.randelshofer.quaqua.leopard.Quaqua15LeopardCrossPlatformLookAndFeel"); +// System.out.println(ch.randelshofer.quaqua.QuaquaManager.getLookAndFeelClassName()); + break; + case 1: + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + break; + case 2: + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"); + break; + case 3: + UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); + break; + case 4: + UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); + break; + case 5: + UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + break; + case 6: + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + break; + default: + System.out.println("TEMA NÂO ESPECIFICADO"); + } + } catch (Exception e) { + Log.out(Util.exeptionToString(e)); + } finally { + } + } +} diff --git a/src/jpkj/UtilFile.java b/src/jpkj/UtilFile.java new file mode 100644 index 0000000..a286ce7 --- /dev/null +++ b/src/jpkj/UtilFile.java @@ -0,0 +1,371 @@ +package jpkj; +//teste + +import antlr.CharBuffer; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.JPanel; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileSystemView; +import org.apache.commons.io.IOUtils; + +public class UtilFile { + + static public void deleteDirectory(File path) { + if (path == null) { + return; + } + if (path.exists()) { + for (File f : path.listFiles()) { + if (f.isDirectory()) { + deleteDirectory(f); + f.delete(); + } else { + f.delete(); + } + } + path.delete(); + } + } + + /** + * Grava um texto em um UtilFile + * + * @param UtilFile O caminho + nome do UtilFile + * @param texto O texto a aser gravado + */ + public static void writeBIN(String arquivo, byte[] texto) { + try { + String filename = arquivo; + FileOutputStream out = new FileOutputStream(filename); + out.write(texto); + out.flush(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Grava um texto em um UtilFile + * + * @param UtilFile O caminho + nome do UtilFile + * @param texto O texto a aser gravado + */ + public static void write(String arquivo, String texto) { + try { + FileWriter fw = new FileWriter(arquivo); + fw.write(texto); + fw.flush(); + fw.close(); + } catch (Exception e) { + } + } + + public static File selectFile(String pasta_inicial, String descricao) { + if (pasta_inicial.trim().isEmpty()) { + pasta_inicial = System.getProperty("user.dir"); + } + return selectFile(pasta_inicial, new String[]{"."}, descricao); + } + + public static File saveFile(String pasta_inicial, String descricao) { + if (pasta_inicial.trim().isEmpty()) { + pasta_inicial = System.getProperty("user.dir"); + } + JFileChooser jfc = new JFileChooser(pasta_inicial); + jfc.setDialogType(JFileChooser.SAVE_DIALOG); + int r = jfc.showOpenDialog(null); + if (r == JFileChooser.APPROVE_OPTION) { + return jfc.getSelectedFile(); + } + return null; + } + + /** + * Inicia um seletor de ARQUIVOS + * + * @param pasta_inicial pasta inicial + * @param filtro final do UtilFile + * @param descricao descrição do UtilFile + * @return UtilFile selecionado + */ + public static File selectFile(String pasta_inicial, String[] filtro, String descricao) { + if (pasta_inicial.trim().isEmpty()) { + pasta_inicial = System.getProperty("user.dir"); + } + final ArrayList sis = new ArrayList(); + sis.addAll(Arrays.asList(filtro)); + final String desc = descricao; + JFileChooser jfc = new JFileChooser(pasta_inicial, FileSystemView.getFileSystemView()); + jfc.setFileFilter(new FileFilter() { + @Override + public boolean accept(File file) { + for (int i = 0; i < sis.size(); i++) { + if (file.getName().contains(sis.get(i).toString()) || file.isDirectory()) { + return true; + } + } + return false; + } + + @Override + public String getDescription() { + return desc; + } + }); + int r = jfc.showOpenDialog(null); + if (r == JFileChooser.APPROVE_OPTION) { + return jfc.getSelectedFile(); + } + return null; + } + + /** + * Inicia um seletor de PASTAS + * + * @param pasta_inicial pasta inicial + * @return Pasta selecionada + */ + public static File selectFolder(String pasta_inicial) { + JFileChooser jfc = new JFileChooser(pasta_inicial); + jfc.setFileSelectionMode(JFileChooser.OPEN_DIALOG); + jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + jfc.setFileFilter(new FileFilter() { + @Override + public boolean accept(File file) { + if (file.isDirectory()) { + return true; + } + return false; + } + + @Override + public String getDescription() { + return "Pastas"; + } + }); + int r = jfc.showOpenDialog(null); + if (r == JFileChooser.APPROVE_OPTION) { + return jfc.getSelectedFile(); + } + return null; + } + + /** + * Verifica se o UtilFile ou pasta existe + * + * @param UtilFile Objeto do tipo file. + * @return True para se o UtilFile ou pasta existe. + */ + public static boolean exists(File arquivo) { + return arquivo.exists(); + } + + /** + * Verifica se o UtilFile ou pasta existe + * + * @param UtilFile Texto com o caminho do UtilFile ou pasta + * @return true para se o UtilFile ou pasta existe. + */ + public static boolean exists(String arquivo) { + return new File(arquivo).exists(); + } + + /** + * Carrega todo o UtilFile em uma String. + * + * @param UtilFile Caminho com o nome do UtilFile + * @return Todo o conteudo do UtilFile. + */ + public static String load(File arquivo) { + String retorno = ""; + try { + retorno = load(arquivo.getPath()); + } catch (Exception e) { + } + return retorno; + } + + public static byte[] loadBIN(File arquivo) { + byte[] b = null; + try { + b = IOUtils.toByteArray(new FileInputStream(arquivo)); + } catch (Exception e) { + } + return b; + } + + /** + * Carrega todo o UtilFile em uma String. + * + * @param UtilFile Caminho com o nome do UtilFile + * @return Uma lista com todo o conteudo do UtilFile. + */ + public static ArrayList loadLines(File arquivo) { + ArrayList retorno = new ArrayList(); + try { + FileReader fr = new FileReader(arquivo); + BufferedReader br = new BufferedReader(fr); + String linha = null; + while ((linha = br.readLine()) != null) {//Em teoria só é null no final + retorno.add(linha); + } + } catch (Exception e) { + } + return retorno; + } + + /** + * Carrega todo o UtilFile em uma String. + * + * @param UtilFile Caminho com o nome do UtilFile + * @return Todo o conteudo do UtilFile. + */ + public static String load(String arquivo) { + String retorno = ""; + try { + + FileInputStream stream = new FileInputStream(arquivo); + FileChannel channel = stream.getChannel(); + ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); + + String text = ""; + while (channel.read(buffer) != -1) { + buffer.flip(); + java.nio.CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer); + text = charBuffer.toString(); + buffer.clear(); + } + retorno = text; + channel.close(); + stream.close(); +// FileReader fr = new FileReader(arquivo); +// BufferedReader br = new BufferedReader(fr); +// String linha = null; +// while ((linha = br.readLine()) != null) { +// retorno += linha + "\n"; +// } +// br.close(); + } catch (Exception e) { + } + return retorno; + } + + /** + * Carrega todo o UtilFile em uma String. + * + * @param UtilFile Caminho com o nome do UtilFile + * @return Uma lista com full o conteudo do UtilFile. + */ + public static ArrayList loadLines(String arquivo) { + ArrayList retorno = new ArrayList(); + try { + FileReader fr = new FileReader(arquivo); + BufferedReader br = new BufferedReader(fr); + String linha = null; + while ((linha = br.readLine()) != null) {//Em teoria só é null no final + retorno.add(linha); + } + } catch (Exception e) { + } + return retorno; + } + + /** + * Redimenciona o UtilFile de imagem em formato jpg + * + * @param imagem + * @param largura + * @param altura + */ + public static void resizeImage(File imagem, int largura, int altura) { + try { + BufferedImage imagemm = ImageIO.read(imagem); + int new_w = largura, new_h = altura; + BufferedImage new_img = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB); + Graphics2D g = new_img.createGraphics(); + g.drawImage(imagemm, 0, 0, new_w, new_h, null); + String formato = imagem.getName().substring(imagem.getName().indexOf(".") + 1).toUpperCase(); + ImageIO.write(new_img, formato, imagem); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Redimenciona o UtilFile de imagem em formato jpg + * + * @param imagem + * @param largura + * @param altura + */ + public static void resizeImage(File imagem, int largura, int altura, String novo_arquivo) { + try { + BufferedImage imagemm = ImageIO.read(imagem); + int new_w = largura, new_h = altura; + BufferedImage new_img = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB); + Graphics2D g = new_img.createGraphics(); + g.drawImage(imagemm, 0, 0, new_w, new_h, null); + String formato = imagem.getName().substring(imagem.getName().indexOf(".") + 1).toUpperCase(); + File nf = new File(novo_arquivo); + ImageIO.write(new_img, formato, nf); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static JPanel openImage(final File image) { + JPanel retorno = new JPanel() { + @Override + protected void paintComponent(Graphics g) { + try { + BufferedImage img = ImageIO.read(image); + g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + return retorno; + } + + public static void copy(String origem, String destino) { + try { + File source = new File(origem); + File destination = new File(destino); + + if (destination.exists()) { + destination.delete(); + } + + FileChannel sourceChannel = null; + FileChannel destinationChannel = null; + + try { + sourceChannel = new FileInputStream(source).getChannel(); + destinationChannel = new FileOutputStream(destination).getChannel(); + sourceChannel.transferTo(0, sourceChannel.size(), + destinationChannel); + } finally { + if (sourceChannel != null && sourceChannel.isOpen()) { + sourceChannel.close(); + } + if (destinationChannel != null && destinationChannel.isOpen()) { + destinationChannel.close(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/jpkj/Zip.java b/src/jpkj/Zip.java new file mode 100644 index 0000000..b640861 --- /dev/null +++ b/src/jpkj/Zip.java @@ -0,0 +1,125 @@ +package jpkj; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Enumeration; +import java.util.Stack; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +public class Zip { + + public static void zip(File file, File outputFile) { + try { + zip(new File[]{file}, outputFile); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void zip(File[] files, File outputFile) throws IOException { + + if (files != null && files.length > 0) { + ZipOutputStream out = new ZipOutputStream( + new FileOutputStream(outputFile)); + Stack parentDirs = new Stack(); + zipFiles(parentDirs, files, out); + out.close(); + } + } + + private static void zipFiles(Stack parentDirs, File[] files, + ZipOutputStream out) throws IOException { + byte[] buf = new byte[1024]; + + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + parentDirs.push(files[i]); + zipFiles(parentDirs, files[i].listFiles(), out); + parentDirs.pop(); + } else { + FileInputStream in = new FileInputStream(files[i]); + String path = ""; + for (File parentDir : parentDirs) { + path += parentDir.getName() + "/"; + } + out.putNextEntry(new ZipEntry(path + files[i].getName())); + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.closeEntry(); + in.close(); + } + } + } + + public static void unzip(File zipFile, File dir) throws IOException { + ZipFile zip = null; + File arquivo = null; + InputStream is = null; + OutputStream os = null; + byte[] buffer = new byte[1024]; + + try { + if (!dir.exists()) { + dir.mkdirs(); + } + if (!dir.exists() || !dir.isDirectory()) { + throw new IOException("O diretório " + dir.getName() + + " não é um diretório válido"); + } + zip = new ZipFile(zipFile); + Enumeration e = zip.entries(); + while (e.hasMoreElements()) { + ZipEntry entrada = (ZipEntry) e.nextElement(); + arquivo = new File(dir, entrada.getName()); + if (entrada.isDirectory() && !arquivo.exists()) { + arquivo.mkdirs(); + continue; + } + if (!arquivo.getParentFile().exists()) { + arquivo.getParentFile().mkdirs(); + } + try { + is = zip.getInputStream(entrada); + os = new FileOutputStream(arquivo); + int bytesLidos = 0; + if (is == null) { + throw new ZipException("Erro ao ler a entrada do zip: " + + entrada.getName()); + } + while ((bytesLidos = is.read(buffer)) > 0) { + os.write(buffer, 0, bytesLidos); + } + } finally { + if (is != null) { + try { + is.close(); + } catch (Exception ex) { + } + } + if (os != null) { + try { + os.close(); + } catch (Exception ex) { + } + } + } + } + } finally { + if (zip != null) { + try { + zip.close(); + } catch (Exception e) { + } + } + } + } +} diff --git a/src/jpkj/annotation/Default.java b/src/jpkj/annotation/Default.java new file mode 100644 index 0000000..e39fe62 --- /dev/null +++ b/src/jpkj/annotation/Default.java @@ -0,0 +1,17 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Default { + + String value(); +} diff --git a/src/jpkj/annotation/Id.java b/src/jpkj/annotation/Id.java new file mode 100644 index 0000000..7566d33 --- /dev/null +++ b/src/jpkj/annotation/Id.java @@ -0,0 +1,13 @@ +package jpkj.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +//@Target(ElementType.METHOD) +public @interface Id { + boolean isPk() default true; + boolean isAI() default true; +} diff --git a/src/jpkj/annotation/Type.java b/src/jpkj/annotation/Type.java new file mode 100644 index 0000000..86c7e4d --- /dev/null +++ b/src/jpkj/annotation/Type.java @@ -0,0 +1,16 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Type { + String value(); +} diff --git a/src/jpkj/beans/Date.java b/src/jpkj/beans/Date.java new file mode 100644 index 0000000..a101451 --- /dev/null +++ b/src/jpkj/beans/Date.java @@ -0,0 +1,22 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj.beans; + +import java.io.Serializable; +import javax.swing.JTextField; +import javax.swing.text.Document; +import jpkj.MaskDate; + +public class Date extends JTextField implements Serializable { + + + public Date() { + this.setDocument(new MaskDate()); + } +// @Override +// public Document getDocument() { +// return new MaskDate(); +// } +} diff --git a/src/jpkj/beans/Hour.java b/src/jpkj/beans/Hour.java new file mode 100644 index 0000000..4f88ad0 --- /dev/null +++ b/src/jpkj/beans/Hour.java @@ -0,0 +1,12 @@ +package jpkj.beans; + +import javax.swing.JTextField; +import javax.swing.text.Document; +import jpkj.MaskHour; + +public class Hour extends JTextField { + + public Hour() { + this.setDocument(new MaskHour()); + } +} diff --git a/src/jpkj/beans/Money.java b/src/jpkj/beans/Money.java new file mode 100644 index 0000000..c5306d3 --- /dev/null +++ b/src/jpkj/beans/Money.java @@ -0,0 +1,42 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package jpkj.beans; + +import java.util.regex.Pattern; +import javax.swing.JTextField; +import jpkj.MaskMoney; + +public class Money extends JTextField { + + public void setValue( String valor ) { + setValue( Float.parseFloat( valor.trim() ) ); + } + + public void setValue( Float valor ) { + String tmp = valor + ""; + this.setDocument( new MaskMoney() ); + String tmp2 = tmp.substring( tmp.indexOf( "." ) + 1 ); + int tmp3 = tmp2.length(); + int tmp4 = 2 - tmp3; + for ( int i = 0 ; i < tmp4 ; i++ ) { + tmp += "0"; + } + String tmp5 = tmp.replaceAll( Pattern.quote( "." ) , "" ); + this.setText( tmp5 ); + } + + public Float getValue() { + Float retorno = 0.0f; + if ( !this.getText().trim().isEmpty() ) { + retorno = Float.parseFloat( this.getText() ); + } + return retorno; + } + + public Money() { + this.setDocument( new MaskMoney() ); + } + +} diff --git a/src/jpkj/beans/Number.java b/src/jpkj/beans/Number.java new file mode 100644 index 0000000..6fe8340 --- /dev/null +++ b/src/jpkj/beans/Number.java @@ -0,0 +1,24 @@ +package jpkj.beans; + +import javax.swing.JTextField; +import javax.swing.text.Document; +import jpkj.MaskNumber; + +public class Number extends JTextField { + + public void setValue( int valor ) { + this.setText( valor + "" ); + } + + public int getValue() { + int retorno = 0; + if ( !this.getText().trim().isEmpty() ) { + retorno = Integer.parseInt( this.getText() ); + } + return retorno; + } + + public Number() { + this.setDocument( new MaskNumber() ); + } +} diff --git a/src/jpkj/beans/Table.java b/src/jpkj/beans/Table.java new file mode 100644 index 0000000..a597030 --- /dev/null +++ b/src/jpkj/beans/Table.java @@ -0,0 +1,115 @@ +package jpkj.beans; + +import java.util.ArrayList; +import java.util.HashMap; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import jpkj.Swing; + +public class Table extends JTable { + + public static String columnType_check = "checkbox"; + public static String columnType_combo = "combobox"; + public static String columnType_text = "textfield"; + boolean look = true; + + public void changeColumnType(int column, String type) { + Swing.changeColumnType(this, column, type); + } + + public void look() { + DefaultTableModel modelo = (DefaultTableModel) this.getModel(); + this.getTableHeader().setReorderingAllowed(false); + modelo = new DefaultTableModel() { + @Override + public boolean isCellEditable(int row, int column) { + return false; + } + }; + this.setModel(modelo); + look = true; + } + + public void unLook() { + DefaultTableModel modelo = (DefaultTableModel) this.getModel(); + this.getTableHeader().setReorderingAllowed(true); + modelo = new DefaultTableModel() { + @Override + public boolean isCellEditable(int row, int column) { + return true; + } + }; + this.setModel(modelo); + look = false; + } + + public boolean isLook() { + return look; + } + + public void clearData() { + DefaultTableModel m = (DefaultTableModel) this.getModel(); + m.setNumRows(0); + m.setRowCount(0); + this.setModel(m); + } + + public void clearColumns() { + DefaultTableModel m = (DefaultTableModel) this.getModel(); + m.setColumnCount(0); + this.setModel(m); + } + + public void clearAll() { + clearColumns(); + clearData(); + } + + public void addLine(Object[] line) { + Swing.addLineTable(this, line); + } + + public void addColumn(Object column) { + Swing.addColumnTable(this, column.toString()); + } + + public void addColumns(Object[] columns) { + for (Object c : columns) { + this.addColumn(c); + } + } + + public void setData(ArrayList> dados) { + clearData(); + look(); + clearColumns(); + addColumns(dados.get(0).keySet().toArray()); + addData(dados); + } + + public void setData(ArrayList> dados, String[] colunas) { + clearData(); + look(); + clearColumns(); + addColumns(colunas); + addData(dados); + } + + public void removeAt(int index) { + if (index > -1) { + DefaultTableModel modelo = (DefaultTableModel) this.getModel(); + modelo.removeRow(index); + this.setModel(modelo); + } + } + + public void addData(ArrayList> dados) { + for (HashMap d : dados) { + ArrayList linha = new ArrayList(); + for (String i : dados.get(0).keySet()) { + linha.add(d.get(i)); + } + this.addLine(linha.toArray()); + } + } +}