lunes, 30 de abril de 2007

Conocer mi versión del Kernel

Para conocer cual es la versión del kernel que estás ejecutando:

uname -r

Leer un String de un Blob

Leer un String de un Blob


Método para leer un String que por necesidades de tamaño se introduce en un blob. Al método se le pasa el resultSet y el nombre del campo en el que se encuentra el blob.


public String leerBlob(ResultSet rs,String blob){
String returndata="";
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
BufferedInputStream bis;
try {
bis = new BufferedInputStream(rs.getBinaryStream(blob));
byte[] bindata=new byte[1024];
int bytesread = 0;
try {
if ( !rs.wasNull() ) {
if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 ) {
baos.write(bindata,0,bytesread);
returndata= baos.toString();
}
bis.close();
}
} catch (IOException e) {
System.out.println("leerBlob -- Se produjo un error en la consulta");
System.out.println(e.getMessage());
}
} catch (SQLException ex) {
System.out.println("leerBlob -- Se produjo un error en la consulta");
System.out.println(ex.getMessage());
}
return returndata;
}

RecorteX - Recortes de código útiles.

lunes, 23 de abril de 2007

Struts: Action en el struts-config

http://struts.apache.org/1.x/userGuide/building_controller.html

4.7 The ActionMapping Implementation

In order to operate successfully, our controller servlet needs to know several things about how each request URI should be mapped to an appropriate Action class. The required knowledge has been encapsulated in a Java class named ActionMapping, the most important properties are as follows:

  • type - Fully qualified Java class name of the Action implementation class used by this mapping.
  • name - The name of the form bean defined in the config file that this action will use.
  • path - The request URI path that is matched to select this mapping. See below for examples of how matching works and how to use wildcards to match multiple request URIs.
  • unknown - Set to true if this action should be configured as the default for this application, to handle all requests not handled by another action. Only one action can be defined as a default within a single application.
  • validate - Set to true if the validate method of the action associated with this mapping should be called.
  • forward - The request URI path to which control is passed when this mapping is invoked. This is an alternative to declaring a type property.

4.8 Writing Action Mappings

How does the controller servlet learn about the mappings you want? It would be possible (but tedious) to write a small Java class that simply instantiated new ActionMapping instances, and called all of the appropriate setter methods. To make this process easier, the framework uses the Jakarta Commons Digester component to parse an XML-based description of the desired mappings and create the appropriate objects initialized to the appropriate default values. See the Jakarta Commons website for more information about the Digester.

The developer's responsibility is to create an XML file named struts-config.xml and place it in the WEB-INF directory of your application. The format of this document is described by the Document Type Definition (DTD) maintained at http://struts.apache.org/dtds/struts-config_1_3.dtd. This chapter covers the configuration elements that you will typically write as part of developing your application. There are several other elements that can be placed in the struts-config file to customize your application. See Configuring Applications for more about the other elements in the framework's configuration file.

The controller uses an internal copy of this document to parse the configuration; an Internet connection is not required for operation.

The outermost XML element must be . Inside of the element, there are three important elements that are used to describe your actions:


This section contains your form bean definitions. Form beans are descriptors that are used to create ActionForm instances at runtime. You use a element for each form bean, which has the following important attributes:
  • name: A unique identifier for this bean, which will be used to reference it in corresponding action mappings. Usually, this is also the name of the request or session attribute under which this form bean will be stored.
  • type: The fully-qualified Java classname of the ActionForm subclass to use with this form bean.

This section contains your global forward definitions. Forwards are instances of the ActionForward class returned from an Action's execute method. These map logical names to specific resources (typically JSPs), allowing you to change the resource without changing references to it throughout your application. You use a element for each forward definition, which has the following important attributes:
  • name: The logical name for this forward. This is used in your Action's execute method to forward to the next appropriate resource. Example: homepage
  • path: The context relative path to the resource. Example: /index.jsp or /index.do
  • redirect: True or false (default). Should the ActionServlet redirect to the resource instead of forward?

This section contains your action definitions. You use an element for each of the mappings you would like to define. Most action elements will define at least the following attributes:
  • path: The application context-relative path to the action.
  • type: The fully qualified java classname of your Action class.
  • name: The name of your element to use with this action
Other often-used attributes include:
  • parameter: A general-purpose attribute often used by "standard" Actions to pass a required property.
  • roles: A comma-delimited list of the user security roles that can access this mapping.
For a complete description of the elements that can be used with the action element, see the configuration DTD or the online DTDDoc docs, and the ActionMapping documentation.

4.8.1 ActionMapping Example

Here's a mapping entry based on the MailReader example application. The MailReader application now uses DynaActionForms. But in this example, we'll show a conventional ActionForm instead, to illustrate the usual workflow. Note that the entries for all the other actions are left out:



name="logonForm"
type="org.apache.struts.webapp.example.LogonForm" />

type="org.apache.struts.action.ActionForward">
name="logon"
path="/logon.jsp"
redirect="false" />


path="/logon"
type="org.apache.struts.webapp.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp"
unknown="false"
validate="true" />


First the form bean is defined. A basic bean of class "org.apache.struts.webapp.example.LogonForm" is mapped to the logical name "logonForm". This name is used as a request attribute name for the form bean.

The "global-forwards" section is used to create logical name mappings for commonly used presentation pages. Each of these forwards is available through a call to your action mapping instance, i.e. mapping.findForward("logicalName").

As you can see, this mapping matches the path /logon (actually, because the MailReader example application uses extension mapping, the request URI you specify in a JSP page would end in /logon.do). When a request that matches this path is received, an instance of the LogonAction class will be created (the first time only) and used. The controller servlet will look for a bean in request scope under key logonForm, creating and saving a bean of the specified class if needed.

Optional but very useful are the local "forward" elements. In the MailReader example application, many actions include a local "success" and/or "failure" forward as part of an action mapping.


path="/editSubscription"
type="org.apache.struts.webapp.example.EditSubscriptionAction"
name="subscriptionForm"
scope="request"
validate="false">
name="failure"
path="/mainMenu.jsp"/>
name="success"
path="/subscription.jsp"/>

Using just these two extra properties, the Action classes are almost totally independent of the actual names of the presentation pages. The pages can be renamed (for example) during a redesign, with negligible impact on the Action classes themselves. If the names of the "next" pages were hard coded into the Action classes, all of these classes would also need to be modified. Of course, you can define whatever local forward properties makes sense for your own application.

The configuration file includes several other elements that you can use to customize your application. See Configuring Applications for details.

4.9 Using ActionMappings for Pages

Fronting your pages with ActionMappings is essential when using modules, since doing so is the only way you involve the controller in the request -- and you want to! The controller puts the application configuration in the request, which makes available all of your module-specific configuration data (including which message resources you are using, request-processor, and so forth).

The simplest way to do this is to use the forward property of the ActionMapping:

4.10 Using Wildcards in ActionMappings

[Since Apache Struts 1.2.0] As an application grows in size, so will the number of action mappings. Wildcards can be used to combine similar mappings into one more generic mapping.

The best way to explain wildcards is to show an example and walk through how it works. This example modifies the previous mapping in the ActionMapping Example section to use wildcards to match all pages that start with /edit:


path="/edit*"
type="org.apache.struts.webapp.example.Edit{1}Action"
name="{1}Form"
scope="request"
validate="false">
name="failure"
path="/mainMenu.jsp"/>
name="success"
path="/{1}.jsp"/>

The "*" in the path attribute allows the mapping to match the request URIs /editSubscription, editRegistration, or any other URI that starts with /edit, however /editSubscription/add would not be matched. The part of the URI matched by the wildcard will then be substituted into various attributes of the action mapping and its action forwards replacing {1}. For the rest of the request, the framework will see the action mapping and its action forwards containing the new values.

Mappings are matched against the request in the order they appear in the framework's configuration file. If more than one pattern matches the last one wins, so less specific patterns must appear before more specific ones. However, if the request URL can be matched against a path without any wildcards in it, no wildcard matching is performed and order is not important.

Wildcard patterns can contain one or more of the following special tokens:

* Matches zero or more characters excluding the slash ('/') character.
** Matches zero or more characters including the slash ('/') character.
\character The backslash character is used as an escape sequence. Thus \* matches the character asterisk ('*'), and \\ matches the character backslash ('\').

In the action mapping and action forwards, the wildcard-matched values can be accessed with the token {N} where N is a number from 1 to 9 indicating which wildcard-matched value to substitute. The whole request URI can be accessed with the {0} token.

The action mapping attributes that will accept wildcard-matched strings are:

  • attribute
  • catalog
  • command
  • forward
  • include
  • input
  • multipartClass
  • name
  • parameter
  • prefix
  • roles
  • suffix
  • type
Also, the action mapping properties (set using the syntax) will accept wildcard-matched strings in their value attribute.

The action forward attributes that will accept wildcard-matched strings are:

  • catalog
  • command
  • path
Like the action mapping, the action forward properties (set using the syntax) will accept wildcard-matched strings in their value attribute.

miércoles, 11 de abril de 2007

Loogic.com Tras el First Tuesday Madrid

Fantástico comienzo para el primer First Tuesday en Madrid de la era post burbuja.

Expectación creo que es la palabra que mejor define lo que he podido ver hoy en Negone. No lo he contado pero debíamos ser entorno a los 100 emprendedores, empresarios e inversores los que nos hemos reunido para hacer networking y escuchar las interesantes experiencias de Rodolfo Carpintier (Inversor), Roberto Saint-Malo (Inversor) y Gustavo García (Emprendedor).

Digo expectación porque todos esperábamos la respuesta a la pregunta del millón: Hay inversión en negocios 100% Internet? Y aunque no se ha podido responder a esta pregunta con claridad lo cierto es que el movimiento está, que los inversores están interesados por entrar en proyectos de Internet y que emprendedores hay suficientes como para satisfacer esas necesidades de inversión.

Me ha llamado especialmente la atención en el First Tuesday Madrid la presencia internacional, no he profundizado mucho en ello pero tengo la sensación de que empresarios y emprendedores europeos están eligiendo España como base para lanzar sus proyectos a nivel internacional.

También quiero destacar las intervenciones de Rodolfo Carpintier que para mi han sido especialmente interesantes. Se dice que Rodolfo fue la primera persona en España en usar el email (cuando yo acababa de nacer) no se si esto estará contrastado pero lo cierto es que Rodolfo es de las personas que mejor conoce Internet en España y eso se nota con claridad cuando habla.

Y tras el encuentro de Networking he tenido la suerte de asistir a la cena de negocios junto con otras 20 personas de muy distintos perfiles pero con la pasión por los negocios como común denominador.

Me hubiera gustado tomar notas durante la cena porque se ha hablado de temas realmente interesantes, se han dado cifras de inversión y de negocio (ya sabeis lo que me gustan las cifras) y se ha hablado de los nuevos proyectos de todos los que estábamos allí reunidos.

Para terminar mencionar una propuesta que ha surgido de la cena, comenzar una campaña viral para fomentar el ahorro energético y así ayudar en lo posible a luchar contra el cambio climático. Sobre esto comentaré mañana más en un post específico.

Actualización: Carlos Blanco y Ángel María también lo comentan.



Loogic.com Tras el First Tuesday Madrid

Twitter and Jott Vulnerable to SMS and Caller ID Spoofing

Both Twitter and Jott authenticate users by their phone number. Twitter does this by validating users based upon the source of SMS messages sent to the phone number 40404 (US), and Jott does this by trusting the incoming Caller ID when someone calls 877-568-848. From a security perspective this means the following:

  • Anyone who knows your phone number can update your Twitter page by spoofing a SMS message, i.e. post a Twitter entry as you.
  • Anyone who knows your phone number can spoof his or her caller ID to send a Jott message as you.

Módulo UML para Netbeans 5.5

Una de las características para Netbeans 5.5 que no pudo estar lista cuando su liberación fue este impresionante módulo UML que ha sido liberado esta semana.

Este módulo permite crear los siguientes diagrams UML:
de Actividad, de Clases, de Colaboración, de Componentes, de Despliegue, de Secuencia, de Estado y de Casos de Uso. Además permite generar código a partir de los diagramas y viceversa, así como mantener la sincronización entre los diagramas y el código. Incluso tiene predefinidos un conjunto de 23 patrones de diseño para implementar en tus diagramas.

Puedes ver capturas de pantalla en este sitio y puedes obtenerlo desde la opción de Actualizar de Netbeans.

http://www.netbeans.org/products/uml/index.html

javaHispano. Tu lenguaje, tu comunidad. (Cañamo v0.8-dev)

Comunicaciones y ocio en una casa domótica | CONSUMER.es EROSKI

Interesante inforgrafía aplicaciones informáticas de ocio en tu casa.

Comunicaciones y ocio en una casa domótica | CONSUMER.es EROSKI

Twitter: llega el 'microblogging' [Pag. 1 de 2] | CONSUMER.es EROSKI

¿Para qué sirve Twitter? Esta pregunta trae de cabeza a los expertos. Casi todos coinciden en que el servicio ha llegado para quedarse, pues tanto su simplicidad como sus posibilidades son inmensas. Se trata de dar de alta una página personal desde la que simplemente se van escribiendo frases de menos 144 caracteres en las que el usuario cuenta lo qué está haciendo. Sus seguidores (generalmente amigos, pero también internautas desconocidos), reciben en forma de mensaje la frase escrita y a su vez escriben en sus páginas su vida cotidiana. Así, cada usuario se convierte en un 'microblogger' que publica las nimiedades de su vida en forma de entradas cortas y con una elevada frecuencia de actualización. ¿Util? De momento sus cientos de miles de usuarios certifican que es altamente adictivo.

Twitter: llega el 'microblogging' [Pag. 1 de 2] | CONSUMER.es EROSKI

domingo, 1 de abril de 2007

Oxado, publicidad para tu sitio web

Acabo de descubrir este servicio de publicidad para la web que nos permite añadir anuncios a nuestro sitio web. Parece que es un buen sustituto/complemento de AdSense.

¿Por qué escoger Oxado?
  • Porque es completamente Gratuito
  • Porque puede darle una fuerte remuneración gracias a las asociaciones exclusivas con los más importantes controles "COST PER clic" del mundo: Overture, Espotting, FindWhat, Mirago, etc.
  • Su sitio web no estará obligado a realizar un tráfico mínimo para inscribirse
  • Pagos mensuales

  • Fácil integración en todo el medio ambiente web.
  • Variados formatos publicitarios para una mejor adaptación a su sitio
  • Más de 2 millones de anuncios que cubren España, Italia, Francia, Inglaterra, Alemania, Holanda, Australia y los Estados Unidos y el Canáda
  • Una selección automática de los anuncios
  • Una difusión inmediata de los anuncios en su sitio web
  • La disponibilidad de estadísticas detalladas
  • La alternancia de la publicidad
  • La calidad de los editores
  • La diversidad de los temas de anuncios, desde grandes bancos hasta empresas locales.
  • El acceso a redes de millares de editores

Oxado