
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.


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.





