Supongamos que tienes un reporte en el que quieres ocultar un listado de una consulta de acuerdo al valor de un parámetro.

Podríamos ocultarlo fácilmente mediante la opción de visibilidad ‘Properties | Visibility | Hide element’ y utilizar una expresión como la siguiente

params[‘ocultarDetalles’].value === true

Screenshot from 2017-06-23 15-02-13

pero la consulta se ejecutaría de cualquier manera, lo que ocasionaría tiempo y procesamiento innecesario.

Para que no se ejecuté la consulta, es necesario remover el elemento que queremos ocultar en el método ‘beforeFactory’ del reporte. Para ello, primero necesitamos especificar el nombre al elemento que queremos ocultar, yo utilicé un grid el cual contiene la tabla de la consulta y lo nombré grdDetalles.
Screenshot from 2017-06-23 15-28-46

Luego selecciona la pestaña ‘Script’ y en la ventana ‘Outline’ selecciona el reporte. Asegurate seleccionar el evento ‘beforeFactory’ y agrega el siguiente script

if (params['ocultarDetalles'].value === true) {
    reportContext.getDesignHandle().findElement("grdDetalles").drop();
}

Screenshot from 2017-06-23 15-01-23

con esto se evita que se realice innecesariamente la consulta.

fuentes:
http://developer.actuate.com/community/forum/index.php?/topic/34143-does-birt-still-execute-a-query-if-an-element-is-hidden/

JHipster is a great tool to start and develop applications, it follows best practices and includes best of breed frameworks and tools.

But, at first it could be too complex to understand. One of the tough things to grasp is liquibase. For us, we had been used to design and build the tables first and then our entities. With jhipster it takes only one step, create your entities and liquibase will take care of the rest. I totally understand why it’s included (they recommend best practices remember), changes to the database are part of any system and as such they should be included as part of the application -and version control, of course-.

To ease the adoption of this tool, we disabled liquibase on production by adding just this lines to the application-prod.yml file

spring:
    profiles:
        include: no-liquibase
...

sources:
http://stackoverflow.com/questions/34559042/disable-liquibase-temporarily-in-jhipster-2-26

To integrate a REST web service with SmartGWT DataSource you have client side data integration mechanisms.

I’ve used this to connect an existing REST web service with SmartGWT controls.

Nevertheless, we have a REST web service wich receives a Path Parameter to update an entity.

    @PUT
    @Path("/proveedores/{id}")
    public Response updateProveedor(@PathParam("id")String id, String request){
        Response response = null;
        try{
            SCRequest<Proveedor> scRequest = Jackson.mapper().readValue(request, new TypeReference<SCRequest<Proveedor>>() {
            });
            Proveedor proveedor = Proveedor.guardar(scRequest.getData());
            response = Response.ok(Jackson.mapper().writeValueAsString(new SCResponse(0, proveedor))).build();
        } catch (Exception e){
            String error = "Ocurrio un problema al actualizar el registro del proveedor";
            log.error(error, e);
            response = Response.serverError().entity(error).build();
        }
        return response;
    }

we need to configure the URL of the RestDataSource dynamically like so in the transformRequest method

public class ProveedoresRestDataSource extends RestDataSource {
    private static final Logger log = Logger.getLogger("ProveedoresRestDataSource");

    public static final ProveedoresRestDataSource INSTANCE = new ProveedoresRestDataSource();
    public static final String API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES = "api/rest/web-gwt-compras/catalogos/proveedores";

    public ProveedoresRestDataSource() {
        setDataURL(API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES);
        setDataFormat(DSDataFormat.JSON);

        OperationBinding create = new OperationBinding(DSOperationType.ADD, API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES);
        create.setDataProtocol(DSProtocol.POSTMESSAGE);
        OperationBinding retrieve = new OperationBinding(DSOperationType.FETCH, API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES);
        OperationBinding update = new OperationBinding(DSOperationType.UPDATE, API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES);
        update.setDataProtocol(DSProtocol.POSTMESSAGE);
        DSRequest updateProperties = new DSRequest();
        updateProperties.setHttpMethod("PUT");
        update.setRequestProperties(updateProperties);
        setOperationBindings(create, retrieve, update);

        DataSourceField fldId = new DataSourceTextField("id");
        fldId.setPrimaryKey(true);
...
        setFields(fldId, ...);
    }

    @Override
    protected Object transformRequest(DSRequest dsRequest) {
        if(DSOperationType.UPDATE.equals(dsRequest.getOperationType())){
            String id = JSOHelper.getAttribute(dsRequest.getData(), "id");
            dsRequest.setActionURL(API_REST_WEB_GWT_COMPRAS_CATALOGOS_PROVEEDORES + "/" + id);
        }
        return super.transformRequest(dsRequest);
    }
}

sources:
http://helpdesk.objects.com.au/java/how-do-i-generate-dynamic-urls-with-smartgwt-and-restdatasource
http://www.smartclient.com/smartgwt/javadoc/

It has been a long time since I updated an app which we have developed with SmartGWT. This time we needed to upload a file to update some catalog.

The SmartGWT documentation explains different ways to achieve this, we’re interested in this part

Background upload without the Smart GWT Server

Achieving background file upload without using the Smart GWT server is also possible although considerably more advanced. In addition to the steps above, create a hidden ** element in the page, and **use DynamicForm.target to target the form submission at this IFRAME. In order receive a callback notification when the upload completes, after processing the file upload, your server should output HTML content for the IFRAME that includes a block which will navigate out of the IFRAME (generally via the JavaScript global “top”) and call a global method you have declared as a callback.

So, the first thing we are going to need is the server side service to receive such file. This app had REST web services with Apache CXF already working, so we should use this same framework (credit goes to javatips for this).

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

@Path("catalogos")
public class CatalogosREST {
    private final Logger log = LoggerFactory.getLogger(CatalogosREST.class);

    private String getFileName(MultivaluedMap<String, String> header) {
        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                String exactFileName = name[1].trim().replaceAll("\"", "");
                return exactFileName;
            }
        }
        return "unknown";
    }

    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response uploadFile(List<Attachment> attachments, @Context HttpServletRequest request) {
        log.debug("se ha recibido una peticion para subir un archivo de proveedores [attachments: {}, request: {}]", attachments, request);
        Response response = null;
        for (Attachment attachment : attachments) {
            DataHandler handler = attachment.getDataHandler();
            try {
                InputStream stream = handler.getInputStream();
                MultivaluedMap<String, String> map = attachment.getHeaders();
                log.debug("headers: {}", map);
                log.debug("fileName: {}", getFileName(map));
                OutputStream out = new FileOutputStream(new File("/tmp/" + getFileName(map)));

                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                stream.close();
                out.flush();
                out.close();
                StringBuilder scriptOnFileUploadFinished = new StringBuilder(
                        "<script type=\"application/javascript\">\n" +
                                "      window.top.onFileUploadFinished();\n" +
                                "    </script>"
                );
                response = Response.ok(scriptOnFileUploadFinished.toString()).build();
            } catch (Exception e) {
                String error = "Ocurrio un error al subir el archivo de proveedores";
                log.error(error, e);
                response = Response.serverError().entity(error).build();
            }
        }
        return response;
    }
}

You can test this REST web service with something like postman.

It’s worth noting that we are returning a block of script tag from this web service. This is necessary to notify our client code that the file upload has finished.

Now, on the client side let’s make our code as per the docs.

final DynamicForm frmUpload = new DynamicForm();
        NamedFrame iframeUpload = new NamedFrame("iframeUpload");
        iframeUpload.setVisible(false);
        frmUpload.setTarget(iframeUpload.getName());
        frmUpload.setEncoding(Encoding.MULTIPART);
        frmUpload.setMethod(FormMethod.POST);
        UploadItem itmUpload = new UploadItem("itmProveedores", "Archivo Proveedores");
        frmUpload.setItems(itmUpload);
        frmUpload.setAction(GWT.getHostPageBaseURL() + "api/catalogos/upload");
        IButton btnUpload = new IButton("Subir archivo proveedorees");
        btnUpload.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                frmUpload.submitForm();
            }
        });

for this to work, we need to register the callback method using JSNI, let’s do that

private static void onFileUploadFinished(){
        SC.say("upload finished");
    }

    private native void registerOnFileUploadFinished()/*-{
        $wnd.onFileUploadFinished = @com.sample.CatalogosForm::onFileUploadFinished();
    }-*/;

...
/*on the constructor, load event or main entry point -it depends on your app-*/
public CatalogosForm(){
    /*initial setup*/
    registerOnFileUploadFinished();
}

and that’s it, your File should upload successfully and display a message when the upload is finished.

sources:
https://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/docs/Upload.html
http://www.javatips.net/blog/cxf-rest-file-upload?page=2
http://stackoverflow.com/questions/8488078/get-call-back-from-servlet-in-gwt-when-upload-file-in-smartgwts-dynamic-form-wi
https://webtoolkit.googleblog.com/2008/07/getting-to-really-know-gwt-part-1-jsni.html
http://stackoverflow.com/questions/2161388/calling-a-parent-window-function-from-an-iframe

Dokku es tu propio Heroku, gracias a Docker. Es un servicio de PaaS (Platform as a Service) para que puedas desplegar (deployear) tus aplicaciones de la misma manera que lo haces en Heroku.

Instalar Dokku es muy sencillo, yo lo hice en una máquina virtual con Ubuntu 16.04 siguiendo la documentación

wget https://raw.githubusercontent.com/dokku/dokku/v0.8.2/bootstrap.sh
sudo DOKKU_TAG=v0.8.2 bash bootstrap.sh

Una vez instalado, abres un navegador con la dirección http://localhost para completar la instalación. Puedes dejar los valores por default o modificarlos de acuerdo a tu configuración. Por ejemplo, si no configuras la IP, el valor por default es la IP publica del servidor. Decidí configurar el servidor con una IP estática y ese fue el valor que puse en el instalador. En el campo Public Key debes poner la llave publica de la computadora desde la cual vas a realizar los deployments (tu máquina de desarrollo). Más adelante puedes agregar otras llaves.
Para obtener tu llave pública, si no tienes una, ejecuta el siguiente comando en tu máquina de desarrollo

ssh-keygen -t rsa

y guarda bien el passphrase que escojas.Luego copia el contenido del archivo ~/.ssh/id_rsa al campo Public Key

Una vez terminado ya puedes crear y deployear aplicaciones.

Para crear una nueva aplicación (vamos a utilizar el ejemplo ruby-rails-sample), primero creala en el servidor dokku mediante el comando

dokku apps:create ruby-rails-sample

luego en tu maquina de desarrollo, clona la aplicación (primero debes agregar tu llave publica a tu cuenta de github)

git clone git@github.com:heroku/ruby-rails-sample.git

ingresa en la carpeta y agrega el repositorio remoto

cd ruby-rails-sample
git remote add dokku dokku@{dokku server ip}

sube la aplicación y mira como se inicia con el comando
gzip: stdin: unexpected end of file
! tar: Unexpected EOF in archive

git push dokku master

la primera vez no pude ejecutar la aplicación de manera exitosa, me aparecía un error

gzip: stdin: unexpected end of file
tar: Unexpected EOF in archive

este error esta documentado en la guía de errores y se debe a una conexión a internet lenta. Para solucionarlo, simplemente ejecuta los siguientes comandos en el servidor de dokku

dokku config:set --global CURL_TIMEOUT=600
dokku config:set --global CURL_CONNECT_TIMEOUT=30

y vuelve a publicar tu aplicación

git push dokku master

Para instalar nodejs hay muchas opciones, cada una con sus pros y contras. Si haces una búsqueda en Google los 2 primeros resultados son:

https://www.digitalocean.com/community/tutorials/como-instalar-node-js-en-ubuntu-16-04-es
https://nodejs.org/en/download/package-manager/

En la primera opción te explican diferentes maneras de instalar nodejs

1.- Desde los repositorios
ejecuta

sudo apt install -y nodejs nodejs-legacy

Ventaja: Fácil
Desventaja: No es la versión más actual (instala la versión 4.2.6) y no instala npm por default (tienes que ejecutar sudo apt install npm)
Resumen: Si no puedes vivir sin una versión reciente, esta opción no es para ti.

2.- Ejecutando un script remoto

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash –
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential

Ventaja: Fácil e incluye la instalación de npm por default. La última línea permite la compilación de paquetes de npm.
Desventaja: Tienes que confiar en que el script remoto no es malicioso
Resumen: Esta es la opción que utilicé porque es la misma que se menciona en la documentación oficial.

3.- Utilizar NVM (Node Version Manager)

… (demasiado largo, referirse al enlace)

Ventaja: Puedes cambiar entre versiones de node.
Desventaja: Es más complejo y en algunos casos marca errores.
Resumen: Apto para usuarios avanzados con requerimientos específicos.

Fuentes:
https://www.google.com.mx/search?hl=es-419&output=search&sclient=psy-ab&q=ubuntu+16.04+install+node&btnG=&oq=&aq=&aqi=&aql=&gs_l=&pbx=1
https://www.digitalocean.com/community/tutorials/como-instalar-node-js-en-ubuntu-16-04-es
https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

EDIT: wordpress removed html sample code and I don’t know how to fix it, in the meantime here’s a link to the source of the article.

I was trying to use a simple checkbox on a form, so I just copied the sample from bootstrap. But I forgot that I was using FuelUX on that form, so it never showed the checkbox. Apparently, there’s a problem mixing checkbox controls -at least in this case-.

So, my form was like this

<form name="editForm" role="form" novalidate>
    <div class="fuelux">
        ...
            <div class="modal-body">
            <div class="wizard" id="myWizard">
            ...

I’m using a wizard control inside a modal dialog. Well, it didn’t show up but the label. So instead, of using the bootstrap checkbox sample code I opted for using the FuelUX checkbox.

<div class="checkbox" id="myCheckbox">


    <span class="checkbox-label">Custom checkbox unchecked on page load</span>

</div>

now the checkbox was displaying just fine. It’s time to bind that the model, so I just added an ng-model attribute like so

<div class="checkbox" id="myCheckbox">


    <span class="checkbox-label">Custom checkbox unchecked on page load</span>

</div>

and it worked great, but only one way. I mean, when you tick the checkbox it updates the model, but if you update the model -anyhow- it won’t change it’s displayed value (won’t check or uncheck). So, you have to update the checkbox state by adding a ng-class attribute, which will add or remove a ‘checked’ class according to the model.

Finally, we have this working like a charm

<div class="checkbox" id="myCheckbox">


    <span class="checkbox-label">Privada</span>

</div>

Sources:
https://docs.angularjs.org/api/ng/directive/ngChecked
https://docs.angularjs.org/api/ng/directive/ngClass