Tuesday, July 31, 2007

Tapestry 5 Preview on OSCON 2007

He visto muchas veces presentaciones sobre algun producto de SW, algunas comienzan con las ventajas que tienen, otras, sobre, los problemas de otras tecnologias que probablemente son la competencia, otras veces, aumentan la tencion comenzando con features o productos anteriores de el equipo o compañía que esta realizando la presentacion, haciendo enfasis en cada uno de los cambios y de ser posible en la revolucion que han creado, todo esto ultimo, lo veo cada vez que veo a ..... si , exacto, ya no dire el nombre, ustedes ya lo saben, la compañía a la que pertenece tiene una manzanita. Pero esta vez fue de las pocas veces en que una diapositiva es tan directa, que tiene frases que yo he escuchado una y otra vez de desarrolladores desperados, no tienen nada que ver con como resolver un problema, ni siquiera un deseo, de darles una clasificacion creo que serian algo asi como un grito desesperado por atencion y aliento divino ... y estas son las frases con las que comenzo Howard Lewis Ship, creador de Tapestry  su exposicion en OSCON ....



A few observations
•❝If ...
•... I have to type one more angle bracket I'll chop off my pinkie! ❞
•... I have to run Ant/Maven one more time I'll staple myself to death! ❞
•... I have to restart Tomcat on more @&*$**@! time I'm going to become a  sheep farmer! ❞
•... I have to write any more &%@&^@ boilerplate code I'll start to listen to
those voices in my head! ❞
•You have a budget for mental investment

En el idioma que sea, yo se que han oido o dicho algo parecido jajaja, esto señores, hizo que me identificara inmediatamente con la situación qu ese estaba describiendo, aumento mi nivel de empatía y por que no de atención


Será que más de una vez dije ... hubiera sido agricultor jajaja, el resto de la presentación es muy sobria y responde pocas preguntas al decir verdad, lastima que no pude ver la ponencia, seguramente fue interesante... más que antes que el estubo Rod Jhonson ...  algun dia quizas ....

Powered by ScribeFire.

Tuesday, July 24, 2007

jdbc & named parameters

Interesante que en el API de java no hay algo tan sencillo como sustitucion de parametros, no numericos posicionales... increible si me preguntan, bueno, abajo se encuentra la solución sencilla a este problema. Simplemente se realiza un wrapper sobre el statement, se parsea, cambiando los parametros por marcas posicionales (?) y creando un mapa que poseera los indices en los que aparece el parametro , no me llevare el credito por este codigo, pues lo encontre en
here, gracias Adam Crume .... creo.... bueno solamente realice un par de modificaciones y agregue un metodo para poder pasar todos los parametros de manera simultanea, ya que en mi caso la necesitaba para completar operaciones de reportes con parametros que vienen de una pagina en el request.

Luego posteare la solución integral por si a alguien le es util



import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

/**
* @author croberto
*
*/
public class NamedParameterStatement {


/** The statement this object is wrapping. */
private final PreparedStatement statement;

/** Maps parameter names to arrays of ints which are the parameter indices.
*/
private final Map indexMap;

private String parsedQuery;

/**
* Creates a NamedParameterStatement. Wraps a call to
* c.{@link Connection#prepareStatement(java.lang.String)
prepareStatement}.
* @param connection the database connection
* @param query the parameterized query
* @throws SQLException if the statement could not be created
*/
@SuppressWarnings("unchecked")
public NamedParameterStatement(Connection connection, String query) throws SQLException {
indexMap=new HashMap();
parsedQuery=parse(query, indexMap);
statement=connection.prepareStatement(parsedQuery);
}


/**
* Parses a query with named parameters.
* The parameter-index mappings are put into the map, and the
* parsed query is returned.
* @param query query to parse
* @param paramMap map to hold parameter-index mappings
* @return the parsed query
*/
@SuppressWarnings("unchecked")
static final String parse(String query, Map paramMap) {

int length=query.length();
StringBuffer parsedQuery=new StringBuffer(length);
boolean inSingleQuote=false;
boolean inDoubleQuote=false;
int index=1;

for(int i=0;i char c=query.charAt(i);
if(inSingleQuote) {
if(c=='\'') {
inSingleQuote=false;
}
} else if(inDoubleQuote) {
if(c=='"') {
inDoubleQuote=false;
}
} else {
if(c=='\'') {
inSingleQuote=true;
} else if(c=='"') {
inDoubleQuote=true;
} else if(c==':' && i+1 Character.isJavaIdentifierStart(query.charAt(i+1))) {
int j=i+2;
while(j j++;
}
String name=query.substring(i+1,j);
c='?'; // replace the parameter with a question mark
i+=name.length(); // skip past the end if the parameter

List indexList=(List)paramMap.get(name);
if(indexList==null) {
indexList=new LinkedList();
paramMap.put(name, indexList);
}
indexList.add(new Integer(index));

index++;
}
}
parsedQuery.append(c);
}

// replace the lists of Integer objects with arrays of ints
for(Iterator itr=paramMap.entrySet().iterator(); itr.hasNext();) {
Map.Entry entry=(Map.Entry)itr.next();
List list=(List)entry.getValue();
int[] indexes=new int[list.size()];
int i=0;
for(Iterator itr2=list.iterator(); itr2.hasNext();) {
Integer x=(Integer)itr2.next();
indexes[i++]=x.intValue();
}
entry.setValue(indexes);
}

return parsedQuery.toString();
}


/**
* Returns the indexes for a parameter.
* @param name parameter name
* @return parameter indexes
* @throws IllegalArgumentException if the parameter does not exist
*/
private int[] getIndexes(String name) {
int[] indexes=(int[])indexMap.get(name);
if(indexes==null) {
throw new IllegalArgumentException("Parameter not found: "+name);
}
return indexes;
}


public void setParameters(Map parameters)throws SQLException{
Set keys = parameters.keySet();
Object param = null;
for (String key : keys) {
param = parameters.get(key);
setObject(key, param);
}
}


/**
* Sets a parameter.
* @param name parameter name
* @param value parameter value
* @throws SQLException if an error occurred
* @throws IllegalArgumentException if the parameter does not exist
* @see PreparedStatement#setObject(int, java.lang.Object)
*/
public void setObject(String name, Object value) throws SQLException {
int[] indexes=getIndexes(name);
for(int i=0; i < indexes.length; i++) {
statement.setObject(indexes[i], value);
}
}


/**
* Sets a parameter.
* @param name parameter name
* @param value parameter value
* @throws SQLException if an error occurred
* @throws IllegalArgumentException if the parameter does not exist
* @see PreparedStatement#setString(int, java.lang.String)
*/
public void setString(String name, String value) throws SQLException {
int[] indexes=getIndexes(name);
for(int i=0; i < indexes.length; i++) {
statement.setString(indexes[i], value);
}
}


/**
* Sets a parameter.
* @param name parameter name
* @param value parameter value
* @throws SQLException if an error occurred
* @throws IllegalArgumentException if the parameter does not exist
* @see PreparedStatement#setInt(int, int)
*/
public void setInt(String name, int value) throws SQLException {
int[] indexes=getIndexes(name);
for(int i=0; i < indexes.length; i++) {
statement.setInt(indexes[i], value);
}
}


/**
* Sets a parameter.
* @param name parameter name
* @param value parameter value
* @throws SQLException if an error occurred
* @throws IllegalArgumentException if the parameter does not exist
* @see PreparedStatement#setInt(int, int)
*/
public void setLong(String name, long value) throws SQLException {
int[] indexes=getIndexes(name);
for(int i=0; i < indexes.length; i++) {
statement.setLong(indexes[i], value);
}
}


/**
* Sets a parameter.
* @param name parameter name
* @param value parameter value
* @throws SQLException if an error occurred
* @throws IllegalArgumentException if the parameter does not exist
* @see PreparedStatement#setTimestamp(int, java.sql.Timestamp)
*/
public void setTimestamp(String name, Timestamp value) throws SQLException
{
int[] indexes=getIndexes(name);
for(int i=0; i < indexes.length; i++) {
statement.setTimestamp(indexes[i], value);
}
}


/**
* Returns the underlying statement.
* @return the statement
*/
public PreparedStatement getStatement() {
return statement;
}


/**
* Executes the statement.
* @return true if the first result is a {@link ResultSet}
* @throws SQLException if an error occurred
* @see PreparedStatement#execute()
*/
public boolean execute() throws SQLException {
return statement.execute();
}


/**
* Executes the statement, which must be a query.
* @return the query results
* @throws SQLException if an error occurred
* @see PreparedStatement#executeQuery()
*/
public ResultSet executeQuery() throws SQLException {
return statement.executeQuery();
}


/**
* Executes the statement, which must be an SQL INSERT, UPDATE or DELETE
statement;
* or an SQL statement that returns nothing, such as a DDL statement.
* @return number of rows affected
* @throws SQLException if an error occurred
* @see PreparedStatement#executeUpdate()
*/
public int executeUpdate() throws SQLException {
return statement.executeUpdate();
}


/**
* Closes the statement.
* @throws SQLException if an error occurred
* @see Statement#close()
*/
public void close() throws SQLException {
statement.close();
}


/**
* Adds the current set of parameters as a batch entry.
* @throws SQLException if something went wrong
*/
public void addBatch() throws SQLException {
statement.addBatch();
}


/**
* Executes all of the batched statements.
*
* See {@link Statement#executeBatch()} for details.
* @return update counts for each statement
* @throws SQLException if something went wrong
*/
public int[] executeBatch() throws SQLException {
return statement.executeBatch();
}







}//class

Wednesday, July 04, 2007

fotos


Yo se que en estos momentos deberia estar dormido, pero ya que andaba buscando material para hacer una estupida presentación de la U, que mas puedo decirles fui a parar por aqui, desde infectedX , y estas, son fotos que merecen toda la pena ver

High Speed photos


If fire were water photos