
Soy César Olea, programador desktop, Web y de sistemas embebidos. Originario de Ciudad Obregón, Sonora, México.
Actualmente he terminado mi maestría en Ciencias de la Computación y me dedico dar mantenimiento, administrar y programar el sitio aVeralCine.com, escribir en Geek&Roll, el Web-comic geeksofacto y distintos proyectos de programación. Mi trabajo oficial (o sea, el que paga las cuentas) es en Tiempo Development como Senior Software Engineer. Si eres un buen programador, hablas Inglés y te interesa trabajar en una empresa con excelente ambiente laboral y projectos interesantes, estamos buscando gente como tu.
Para contactarme puedes ![]()
enviarme un mensaje si estoy conectado a gTalk.

Geek&Roll es el blog donde escribo sobre programación, cracking, cultura geek, Software Libre, Internet, y más. En conjunto con Axel y Rafyta mantenemos un blog de contenido (casi todo) original.
Debido a que ocurrió un overflow cuando intentamos pagar el dominio, GoDaddy no permitió el acceso a este blog por medio de nuestro dominio. Los detalles no los se, solo que el BigInt que utilizan para guardar la cantidad del pago no alcanzó, y por tanto el overflow, causando todo tipo de problemas.
Gracias por su paciencia. Estamos de vuelta, keep on Geek&Rolling!
Hace poco decidí cambiar de modelo de BlackBerry, de la viejita 8110 a la un poquito más moderna 8520. Al ir a Telcel me dijeron que con mi plan era imposible cambiar al equipo que yo quería, aún cuando quisiera pagar el costo total del mismo.
Como en Telcel me la hicieron difícil, compré el equipo aparte y le cambié el chip. Hasta ahí todo bien, sin embargo al llegar la factura veo que me cobran la conexión de datos, aún cuando mi plan incluye datos ilimitados. En la factura me cobran el plan (con datos ilimitados incluidos) más los datos consumidos. Obviamente algo andaba mal. Después de dos visitas al centro de “atención” al cliente – que de atención no tiene nada – no me pudieron resolver mi problema. Las dos personas que me atendieron coincidían en que “que raro!?!?” y levantaron un reporte.
Gracias a que tengo a una persona conocida que trabaja en el corporativo, después de unos cuantos SMS’s el problema quedó aclarado y resuelto. Bueno, resuelto a medias porque voy a tener que pagar el cargo excesivo.
El problema, y lo que nunca me pudieron explicar en el centro de pseudo-atención, fue que al cambiar de equipo si tienes un plan de datos ilimitados, esto no se te respeta. En ningún lugar te lo indican, tampoco te lo advierten en Telcel. Y lo que es peor, nunca me lo superion resolver. Tuve que usar “palancas” del corporativo para que me resolvieran, ya que los asesores del centro de atención se limitaron a rascarse la cabeza. Nunca me preguntaron ¿No cambió su equipo señor?
Así que si tienen una BlackBerry y deciden cambiar de equipo, antes de meter su chip en el equipo nuevo, vayan a su centro de atención y pidan que les hagan el cambio para evitar cargos excesivos. Esta información la deberían de proporcionar de primera mano en Telcel, pero como siempre con prácticas poco éticas para sacar hasta el último centavo.
No iba a proporcionar información, pero por el coraje que me hicieron pasar les muestro una captura de pantalla de lo que será Everlasting Flame 2.0. Descárguenlo y eviten pagarle más de la cuenta a Telcel.
Finalmente lo inevitable sucedió. George Hotz ha superado las barreras impuestas por el hypervisor del PS3, teniendo acceso total a la memoria del sistema y al CPU. Este es el anuncio oficial:
I have read/write access to the entire system memory, and HV level access to the processor. In other words, I have hacked the PS3.
Lo que sigue es esperar a la implementación de un exploit y ver cómo se desarrolla la comunidad del homebrew alrededor de esta consola.
Tiempo total de hackeo: 5 semanas. Can’t wait.
El PS3. Esta consola de séptima generación, y el tercer miembro de la familia PlayStation. Desde su lanzamiento en Noviembre del 2006 muchos crackers se han dado a la tarea de romper las barreras impuestas por el hypervisor y abrir la posibilidad de ejecutar código de terceros en esta máquina.
Primero que nada, ¿Qué es un Hypervisor? Según la Wikipedia, es un monitor de hardware o software que permite la ejecución de varios sistemas operativos en el mismo hardware. Existen dos tipos: Tipo 1 o nativo son los que corren directamente en el hardware. Tipo 2 son los que corren como cualquier otra aplicación del sistema operativo (como VirtualBox o VMWare)
Una visita a los foros de PS3-Scene revela poca actividad alrededor de la escena del PS3. Hace ya lo que parecen siglos Paradox, uno de los grupos más respetados en el mundo del cracking, anunciaba que tenía un iso loader listo para el PS3. Algo así como el santo grial, que nunca llegó.
Después vino IronPeter, un hacker de Rusia que logró tener acceso a algunos de los registros del RSX (la tarjeta de video del PS3) y con eso permitir la aceleración 2D para aplicaciones que se ejecutan desde OtherOS (GNU/Linux), lo que en teoría significa poder tener juegos y otras aplicaciones como Boxee o XBMC corriendo en el PS3 bajo GNU/Linux. La discusión técnica se encuentra en los foros de PS2Dev. Desgraciadamente la manera para aprovecharse de este bug es por medio de OtherOS, es decir la capacidad que tenían modelos anteriores de ejecutar otro sistema operativo. Hablo en pasado ya que el nuevo PS3 Slim ha eliminado el soporte para OtherOS, cosa que no me sorprende en lo absoluto.
A la fecha no se ha abierto el PS3 al homebrew. Es el turno de Geohot (a.k.a. George Hotz, master del iPhone) de probar suerte. Ya ha creado un blog “On the PlayStation 3” al igual que sucedió con el ahora famoso “Finding JTAG on the iPhone”. Pura lectura técnica y altamente interesante. Si la escena va a reportar adelantos próximamente, este es el lugar para estar atento.
Recién bajé la aplicación de Wordpress para Blackberry y de inmediato quise probar la publicación. Es bastánte cómoda.
Lo que me parece es que si subo una foto me va a poner el tamaño por default y ya. Veamos qué sucede.
Saludos a los visitantes de este blog fantasma :)
Update: en efecto, la foto se subió un poco más grande de lo debido (640px wide), la acabo de reducir desde la PC.
Desde los headquarters (we wish) de Geek & Roll les deseamos una feliz navidad a todos nuestros comentaristas, lurkers, trolls y visitantes ocasionales. Va un abrazo.
Si te da hueva instalar tooooodo el wordpress nomás para evitarte las extensiones .php (o las de tu religión elegida), o de plano no lo necesitas, no te pierdas de ésta fíchur. Suponiendo que vivas en el maravilloso mundo de Apache, puedes arrojar este archivito .htaccess para que te haga el paro instantáneamismamente de quitar las extensiones .php de todos tus archivos, ok ok, en realidad los redirecciona pero es la misma, no?
Si lo que quieres es ahorrarte los horrores de ?var=value&this=siht&foo=barrio y esas cosas del diablo que no le gustan a Google y sus compas, también se puede; sólo tienes que editar unas líneas del archivo para alcanzar la felicidad instantánea. El archivo está así por default:
# RewriteRule ^folder/(.*)/$ /file.php?image=$1
# RewriteRule ^kind$ /category.php?cat=kind
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Las dos líneas que empiezan con el gato (#) son las que pueden habilitar esa onda, por ejemplo en el primer caso, puedes tener el url original:
http://sitio.com/fotos.php?src=verano.jpg&w=300&h=200&zc=1
y con unos cambios hacerlo así: http://sitio.com/fotos/verano especialmente útil si usas TimThumb o algo así.
El segundo caso considera el ejemplo una tienda en línea, o cualquier tipo de sitio que use una base de datos para clasificar varios elementos (o records) en categorías y haga una lista. Por ejemplo, puedes tener: http://mitiendita.com/articulos.php?tipo=jeans
y pasar a: http://mitiendita.com/jeans.
Hay más cosas que se pueden hacer con éste simple código, pero éstas son las más frecuentes. Si se te ocurre alguna otra posibilidad, déjala en los comentarios.
Instalación:
Si alguna vez has usado Google Chrome y lo dejaste para volver a firefox, probablemente tengas el mismo problema que yo tuve: extrañas hacer búsquedas en Google directamente desde la barra de dirección.
De hecho, Firefox hace *casi* lo mismo, sólo que en lugar de llevarte a los resultados de búsqueda este te lleva directamente al primer resultado, o al “I’m feeling lucky”, lo que es mucho menos útil, porque seamos sinceros: una cosa es que te sientas suertudo y otra cosa muy distinta es que encuentres lo que buscas a la primera. Pero bueno, esto es muy sencillo de cambiar:
Listo, ahora puedes buscar desde la barra de direcciones de firefox. Y ya puedes quitar la barra de búsqueda que está a la derecha.
De nada.

iTunes me desespera, nunca he sido fan del programa. Para mi gusto es un programa demasiado restrictivo en cuanto a manejar un iPod se refiere. Supongo que lo hacen así para evitar la piratería, trabajar con DRMs y darle gusto a masoquistas. Cuando quiero reproducir música en Windows, mi gallo es Foobar2000.
Para el que no lo conozca, Foobar2000 es un reproductor minimalista creado por un ex-desarrollador de Nullsoft (los de Winamp). Foobar2000 tiene un SDK para que terceros puedan crear plugins y extender sus capacidades con cosas como visualizador de portadas, espectogramas, convertidores, entre otras cosas. Si buscas un reproductor ligero en recursos con una interfaz minimalista y altamente configurable, definitivamente tienes que probarlo.
Ahora bien, a lo que nos concierne. Además de no gustarme, iTunes es un tabú en la oficina así que mi iPod nano de nosequegeneración no sirve de mucho. No solo eso, sino que aún con iTunes, este se niega a reproducir la música guardada en el iPod. No se a ciencia cierta, pero sospecho que es elitismo de parte de iTunes porque todos los mp3 que tengo fueron puestos ahí por gtkpod. ¿Será que a iTunes no le agrada gtkpod?
Foobar2000 al rescate. Gracias a su SDK, alguien se dio a la tarea de crear un plugin para administrar iPods lo que le permite a Foobar2000 reproducir la música contenida sin preocuparte por borrarla accidentalmente al sincronizarse y, lo que es más importante, sin elitismos. Foobar2000 con el iPod manager plugin reproduce toda mi música, los mismos archivos que iTunes no pudo, sin importar su procedencia.
Lo mejor de todo: la instalación. Descomprime Foobar2000 en cualquier folder. Después descomprime el plugin iPod manager en el folder de components dentro del folder principal de Foobar2000. En Foobar2000 ve a File | iPod | Load library y el resto espero no tener que explicarlo.
iPod – iTunes en Windows = Bliss
Que titulo tan mas pendejo y tan mas viejo. Pero bueno, se trata de que un buen amigo me paso este enlace esta mañana. No pude dejar de interesarme ya que me encantan las teorías de conspiración y más cuando se tratan del gobierno cargándonos la mano! Yeah!
Bueno, para resumir, el enlace habla de que estamos en contacto con vida extraterrestre, al menos de una manera oficial. “The Telegraph” (ni me pregunten quienes son) publico que una entidad gubernamental búlgara (me imagino que científica) oficialmente acepto que estamos en contacto con ETs.
Otro enlace, dice que este es el plan maestro del gobierno gringo, y que Obama, cuando le entreguen su premio nobel de la paz en Oslo el próximo 10 de diciembre, tiene preparado un discurso donde dará la noticia mundial de que queremos lazos con los ETs y que exhortara a todas las naciones a desarmarse para crear un ambiente de paz global. Esto con el fin ultimo de, si, adivinaron, crear un gobierno global y único. Claro seremos cochis con etiquetas en un socialismo asqueroso.
Todo esto como lectura esta al chingazo, y la verdad tengo curiosidad por que sea 10 de diciembre y saber si Obama realmente hablara de esto. Claro que seria emocionante vivir el tiempo en el que la civilización humana de un cambio colectivo global. Porque no hay metas claramente establecidas. Si, tenemos el fenómeno del niño y el fenómeno invernadero y las iniciativas “green” que nos traen las “macs”… ¿Pero realmente a donde llegamos con eso? A ninguna parte. La humanidad sigue de cabeza y sigue habiendo muchas cosas descompuestas.
A lo que voy es a que seria bonito tener una esperanza de que este pedo se va a arreglar y de que algún día llegué un cometa que nos obligue a mandar a una flota de perforadores vestidos de anaranjado que caminen en camara lenta (entre ellos Bruce Willis), y que gracias a eso, todas las personas puedan escuchar en la tele y en la radio mientras ven una explosión en el cielo de victoria. No nos vamos a morir, vamos a sobrevivir, pero tenemos que dejarnos de pendejadas.
Esta muy cabrón pedir un cometa, pero que tal decirle a Obama que cree el caos global y que truene las religiones (como las conocemos) con una noticia de UFOs!!! Seria como otro 911. Nos ayudaría a unirnos para una meta común, global y con metas claramente trazadas!
Ya en serio, en este post no pretendo discutir si estas noticias son ciertas o son solamente delirios de hippies que viven en tiendas de campaña y que queman monos gigantes. Sino compartir lo que no pude evitar pensar a lo largo del día.
Imagine que era completamente aceptado que venían seres de otra civilización. Obviamente mas avanzados que nosotros, porque ni modo que los saquemos de los hormigueros. Hasta los viajes a la luna los quieren privatizar por que odiamos el socialismo. E imagine que teníamos que darles la bienvenida y desde ahorita se los digo, yo no quiero ser el embajador intergalactico que les tenga que explicar las siguientes cosas:
En serio, puedo hacer esto todo el dia.
Ahora les pregunto a ustedes. ¿Que serian capaces de dar a cambio de que no existieran todas estas cosas sin sentido? En serio… Yo se que la mayoría no tienen bentlis de esos… Pero no los necesitan. ¿Que tal sacrificar el agua caliente y el aire acondicionado con tal de que el resto del mundo tuviera lo mismo que tu?
Pinche botón de reset… Donde chingados estas!

Los dejo con esta foto para hacerles la barba a los ETs y a Obama, uno nunca sabe lo que pueda pasar!
** Nota: El chiste de estereotipos raciales fue incluido para restarle seriedad al escrito y para poder decir que el post entero es broma en caso de que Obama no diga nada el dia 10 de Diciembre… Que quemadoooon!

A TextMate syntax compatible source editing widget. Current adapters are for SWT.

An AJAX request contains the same request/response information as a traditional HTTP request. You can set cookies on the client once the async callback is executed, etc.
REST stands for Representational State Transfer, and it was proposed in a doctorate dissertation (see here). It uses the four HTTP methods GET, POST, PUT and DELETE to execute different operations. This in contrast to SOAP for example, which creates new arbitrary commands (verbs) like getAccounts() or applyDiscount()
A REST API is a set of operations that can be invoked by means of any the four verbs, using the actual URI as parameters for your operations. For example you may have a method to query all your accounts which can be called from /accounts/all/ this invokes a HTTP GET and the 'all' parameter tells your application that it shall return all accounts.
If you want to create your own borderless window, instead of using a Frame/JFrame use a Window/JWindow. Frame/JFrame are extensions to Window/JWindow that provide borders and the maximize, minimize and close buttons. Usually those widgets are provided by the OS, but you can override them.
When you compile something in Java, the compiler generates bytecode. This is native code for the Java Virtual Machine. The JVM then translates the bytecode to native code for your processor/architecture, this is where the JIT happens. Without JIT, the JVM would translate the program one instruction at a time, which is very slow.
While XPath is a great choice, I would recommend JDom if your XML document is not huge, since it loads the entire document in memory.
Using JDom:
try {
SAXBuilder builder = new SAXBuilder();
Document firstDocument = builder.build(firstFile);
Document secondDocument = builder.build(secondFile);
Element firstRoot = firstDocument.getRootElement();
Element secondRoot = secondDocument.getRootElement();
List<Element> sourceListPost = secondRoot.getChild("listPost");
firstRoot.addContent(sourceListPost);
Document merged = new Document(firstRoot);
} catch(JDOMException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
Now merged contains the merged Document. You can serialize it to a file with XMLOutputter.
You don't need an applet, from a grails controller you may use any Java library. Use the Java printing services available to the runtime in javax.print. This is assuming that the printer is installed where the grails runtime is running.
URLDecoder.decode(url);
See related question http://stackoverflow.com/questions/623861/how-do-you-unescape-urls-in-java
I think you would benefit greatly with a build tool, such as ant or maven. You can have a target to compile only one class without building the whole code, or any other related task.
There's nothing wrong with the way you are compiling, it's just cumbersome but certainly not wrong.
That being said, create a src directory to store your .java files, keeping your directory structure coherent with the package structure of your classes. In this case you would have src directory and inside it, directory A and directory B. Inside A put Test1.java and inside B put Test2.java
Then:
javac B/Test2.java
Why Test2.java? Because it depends on A, then the compiler is smart enough to first compile A/Test1.java and then B/Test2.java. At this point you have each .class files inside A and B
To run it:
java B.Test2
My only advise would be don't go that way. As Bill K already said, most implementations would be significantly faster and more complete. Even more important is that there are excellent resources to achieve what you are trying to do: OSGi for example which has Eclipse and Glassfish v3 under its belt.
Personally I implemented something similar to your description, loading plugins at runtime without needing to restart the container. It was a nightmare to maintain and debug. And more important, while it was relatively easy for me to implement new modules (after all, I designed the thing), it was very difficult to program to. I ended up learning a lot about classloaders, but that was it.
If you fix the scaleMod and initialDistance to powers of 2 you could use shifts for faster multiplication and division.
See here for reference.
Check out Web Harvest. It's both a library you can use and a data extraction tool, which sounds to me that's exactly what you want to do. You create XML script files to instruct the scraper how to extract the information you need and from where. The provided GUI is very useful to quickly test the scripts.
Check out the project's samples page to see if it's a good fit for what you are trying to do.
JComboBox constructor can take a ComboBoxModel as argument. DefaultComboBoxModel is a concrete implementation of the ComboBoxModel interface.
So, if you have a Personel class:
class Personel{
String personelName;
int personelId;
//getters, setters
//This will be your display member
@Override
public String toString(){
return this.personelName;
}
}
And supposing you obtained all personel via JDBC and have it stored in a new Vector, you can do:
DefaultComboBoxModel comboModel = new DefaultComboBoxModel(personel);
JComboBox myCombo = new JComboBox(comboModel);
At runtime, you can getModel and setModel to access the JComboBox model. The display member will be Personel's toString() method. The value member will be the actual object stored in the DefaultComboBoxModel vector, in this case a Personel instance.
I suggest you take a look at the API documentation for ComboBoxModel and DefaultComboBoxModel.
You would use a regular expression to search for @username and then turn that to the corresponding link.
I use the following for the @ in PHP:
$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise",
"'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'",
$ret);
With an actionSubmit:
Purpose
Creates a submit button that maps to a specific action, which allows you to have multiple submit buttons in a single form. Javascript event handlers can be added using the same parameter names as in HTML.
From the Grails reference docs.
Since you are using JDK6, you can use classpath wildcards: CLASSPATH=".:/home/phoenies/jdk1.6.0_17/lib/*" will match all JARS inside lib/
Check out http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html there's a section called "Understanding class path wildcards"
For it to work, the phpBB code would have to be looking for POSTed login credentials, which may not be the case. phpBB would need to specifically look for a post variable named user_name and user_pass which again may not be the case.
The example you are following is more a tutorial for using the POST method in HTTP from Java. If you want to see the results try it with the page they posted in the article located at http://www.1your.com/drupal/sample%5Flogin.php
As a suggestion, you could use something like Firebug to analyze the request/response HTTP transaction and from there you know what phpBB is expecting at the server side.
I'm trying to get a simple layout working under GWT 2.0 using UiBinder. The layout I'm trying to get is one that mimic Java's BorderLayout in where you can specify different panels in the north, south, east, west and center directions; for that I'm using DockLayoutPanel. I would like to get a header and footer, both with fixed width. The remaining viewport space would be occupied by the widget assigned to the DockLayoutPanel center slot.
The current .ui.xml file I've got is:
<g:DockLayoutPanel unit='EM'>
<g:north size='2'>
<g:HTML>HEADER</g:HTML>
</g:north>
<g:south size='2'>
<g:HTML>FOOTER</g:HTML>
</g:south>
<g:center>
<g:HTML>
<div id='loginform'>Hello!</div>
</g:HTML>
</g:center>
</g:DockLayoutPanel>
The browser only renders HEADER at the top left corner. How can I achieve the layout I'm looking for? It seems that there's more CSS you've got to know before you can use GWT layout panels, but that kind of defeats the purpose of creating the UI with it.
You can convert a MySQL result set to JSON easily: http://phpclasses.nlared.com/browse/package/3195.html
For a RESTful interface, basically any hosted PHP script can function as a REST interface for your application.
A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).
If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.
I have a g:select in my view that displays a list of products:
<g:form name="addproductform" action="saveProductToInventory" method="post">
<g:select from="${products}" name="product" value="${it?.id}" />
<g:hiddenField name="inventory.id" value="${inventoryInstance.id}" />
<input class="save" type="submit" value="Save product" />
</g:form>
${products} is a list of all products. If I print the params variable that is passed to the controller, I get this:
[product:Test Product, inventory:[id:1], inventory.id:1, action:saveProductToInventory, controller:inventory]
The product key contains the name, and not the ID which I thought it would contain when I added value="${it?.id}" to the g:select tag.
How do I need to declare the g:select tag to render the product's name as it is right now, but pass the product's id as value?
Check the answers to these other questions:
This is a fairly popular question.
Another option would be IKVM. It's a Java implementation for .NET. Please take a look at this related question, the answers there might help you.
You can push a branch to a remote server, say github. You would first have to do the initial project setup, then clone your project and:
git push <remote repo> <your branch>
The Unsatisfied Link Error can mean many things went wrong. I would use
System.loadLibrary("HelloWorld");
Instead of
System.load();
As TwentyMiles suggested.
Also, when invoking your program you need to (assuming your DLL is on the same directory as your class files:
java -Djava.library.path=. HelloWorld
Here's a simple demo I made that calls a Win32 API function (MessageBox)
class CallApi{
private native String showMessageBox(String msg);
private native double getRandomDouble();
static{
try{
System.loadLibrary("CallApi");
System.out.println("Loaded CallApi");
}catch(UnsatisfiedLinkError e){
//nothing to do
System.out.println("Couldn't load CallApi");
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
CallApi api = new CallApi();
double randomNumber = api.getRandomDouble();
String retval = api.showMessageBox("Hello from Java!\n"+
"The native random number: "+randomNumber);
System.out.println("The native string: "+retval);
}
}
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CallApi */
#ifndef _Included_CallApi
#define _Included_CallApi
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: CallApi
* Method: showMessageBox
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_CallApi_showMessageBox
(JNIEnv *, jobject, jstring);
/*
* Class: CallApi
* Method: getRandomDouble
* Signature: ()D
*/
JNIEXPORT jdouble JNICALL Java_CallApi_getRandomDouble
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
#include "CallApi.h"
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#pragma comment(lib,"user32.lib")
JNIEXPORT jstring JNICALL Java_CallApi_showMessageBox
(JNIEnv *env, jobject thisObject, jstring js)
{
//first convert jstring to const char for use in MessageBox
const jbyte* argvv = (*env)->GetStringUTFChars(env, js, NULL);
char* argv =(char *) argvv;
//Call MessageBoxA
MessageBox(NULL, argv, "Called from Java!", MB_ICONEXCLAMATION | MB_OK);
return js;
}
JNIEXPORT jdouble JNICALL Java_CallApi_getRandomDouble
(JNIEnv *env, jobject thisObject)
{
double num1;
srand((unsigned)(time(0)));
num1 = ((double)rand()/(double)RAND_MAX);
return num1;
}
I compile with the Visual C++ express 2008 cl, removing the -ML flag since it causes an exception when the Java code tries to call the native code:
cl /I"c:\Program Files\Java\jdk1.6.0_10\include" /I"c:\Program Files\Java\jdk1.6.0_10\include\win32" -LD CallApi.c -FeCallApi.dll
Then, to run the code:
java -Djava.library.path=. CallApi
I have an application that takes some input and generates configuration files as output. Since the exact input or output format could change over time, I defined two interfaces: Importer and Exporter.
Each concrete importer or exporter could have different parameters that need to be initialized to work. For example, if the import data is coming from a CSV file you only need the path of the file, but if the data is coming from a database then you need a connection string, username, password, etc. Same thing for exporters.
My implementation currently is:
public interface Importer {
public void setup(Map<String,String> params);
public List<ConfigEntry> getList();
}
public interface Exporter {
public void setup(Map<String,String> params);
public void writeDocument(List<ConfigEntry> entries) throws IOException;
}
The setup method needs to be called before getList() or writeDocument() can be called. I use a Map to keep parameters because each child class can have different parameters.
Is using JavaBean style parameter initialization a preferred way? That means, adding setConnnectionString(), setCSVFilePath(), setX() to each child class.
What are the advantages, disadvantages of these approaches?
For what is worth, I finally nailed it.
The exception I got when trying to save a car was
not-null property references a null or transient value
It was obvious that the engine was null when trying to save, but why? Turns out you have to do:
def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
car.engine.save()
Since engine doesn't belongs to a Car, you don't get cascade save/update/delete which is fine in my case. The solution is to manually save the engine and then save the car.
I'm struggling to get association right on Grails. Let's say I have two domain classes:
class Engine {
String name
int numberOfCylinders = 4
static constraints = {
name(blank:false, nullable:false)
numberOfCylinders(range:4..8)
}
}
class Car {
int year
String brand
Engine engine = new Engine(name:"Default Engine")
static constraints = {
engine(nullable:false)
brand(blank:false, nullable:false)
year(nullable:false)
}
}
The idea is that users can create cars without creating an engine first, and those cars get a default engine. In the CarController I have:
def save = {
def car = new Car(params)
if(!car.hasErrors() && car.save()){
flash.message = "Car saved"
redirect(action:index)
}else{
render(view:'create', model:[car:car])
}
}
When trying to save, I get a null value exception on the Car.engine field, so obviously the default engine is not created and saved. I tried to manually create the engine:
def save = {
def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
if(!car.hasErrors() && car.save()){
flash.message = "Car saved"
redirect(action:index)
}else{
render(view:'create', model:[car:car])
}
}
Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?
You've clearly narrowed it down to two options. Between those two I would recommend to stick to the one with a larger community, since it's easier to get support that way. You already experienced that here, where Grails is familiar territory for many, but that's not the case for Aribaweb.
Also I've found that it really helps to try and do a simple but complete example project in both tools. Come up with a general design, and see how much time and effort it takes you to implement it in both frameworks. You can look for the following symptoms:
Personally, that framework would be Grails.
I'm having a hard time figuring this validation problem. I have one parent domain class defined as follows:
class Person {
String fullName
List telephones = []
static hasMany = [telephones : Telephone]
static constraints = {
fullName(size:3..50, blank:false, nullable:false)
}
}
Then a sublcass:
class SalesAdvisor extends Person{
Float comission //In percentage
Portfolio customerPortfolio
Inventory inventory
static constraints = {
comission(range:0..100, scale:2, nullable:false)
customerPortfolio(nullable:false)
inventory(nullable:false)
}
}
In the SalesAdvisorController I save SalesAdvisor instances:
def save = {
def portfolio = new Portfolio()
def inventory = new Inventory(name:'${params.fullName}Inventory', description:"${params.fullName}'s Inventory")
params.customerPortfolio = portfolio
params.inventory = inventory
def salesAdvisor = new SalesAdvisor(params)
if(!salesAdvisor.hasErrors() && salesAdvisor.save()){
log.info("New instance of SalesAdvisor saved.")
redirect(action:show, id:salesAdvisor.id)
}else{
log.error("There was an error saving the sales advisor.")
salesAdvisor.errors.allErrors.each{
println it.code
}
render(view:'create', model:[salesAdvisor:SalesAdvisor])
}
}
In order to display any errors, in the 'create' view I have:
<g:hasErrors bean="${salesAdvisor}">
<div class="errors">
<g:renderErrors bean="${salesAdvisor}" as="list" />
</div>
</g:hasErrors>
Validation seems to be working fine. However if I submit a string instead of a float for the comission field, in logs I can see "typeMismatch" but the view renders nothing! The message.properties file has a default entry for typeMismatch. Same thing for the fullName field, in logs I can see "nullable" and "blank" errors, but the view renders nothing.
I'm guessing it's more the view's fault than the controller or the domain, since unit tests behave like they should.





