While I was working with a lot of reports, it made sense to use a standard file name for all the files. This was an afterthought, so it required me to rename the files. I was hoping Ubuntu Nautilus had this option, but for my current version -16.04- it doesn’t. That feature is expected to land in 17.04. in the meantime you can install nautilus-renamer which offers the same feature.

Just download the .deb package from the nautilus-renamer launchpad page and install it with

sudo dpkg -i nautilus-renamer_4.0-quantal_all.deb
sudo apt install -f
killall nautilus

It des not work if parent folders contain spaces in their name and it does not support unicode characters. I guess the nautilus version for 17.04 should work with these.

Then, just open a nautilus window and select a bunch of files, right click and select ‘rename…’ or just press F2.

done!

sources:
http://www.omgubuntu.co.uk/2016/06/nautilus-batch-rename-feature-coming-gnome-3-22
https://launchpad.net/nautilus-renamer
http://www.omgubuntu.co.uk/2016/08/quick-look-new-features-nautilus-3-22
https://launchpad.net/~gnome3-team/+archive/ubuntu/gnome3

We have a bunch of tables per office, each on its own schema in an Oracle Database.

For simplicity, we have created views on this tables and synonyms to access this views from one single schema. Hibernate supports mapping entities to synonyms, so there’s nothing more we need to do on our entities. But we still want to be able to add and modify underlying data.

To achieve this we had to create views and triggers like so

SET DEFINE OFF;
CREATE OR REPLACE FORCE VIEW CENTRAL.VPARTES
(
   SID_PARTE,
   ...
)
AS
   SELECT 'OF001' SID_OFICINA,
          T.SID_PARTE,
          ...
     FROM OFICINA001.TPARTES T
    WHERE 1 = 1 AND T.NESTATUS IN (1, 2)
   UNION ALL
   SELECT 'OF002' SID_OFICINA,
          T.SID_PARTE,
          ...
     FROM OFICINA002.TPARTES T
    WHERE 1 = 1 AND T.NESTATUS IN (1, 2);


CREATE OR REPLACE TRIGGER CENTRAL.TG_VPARTES_UPD
INSTEAD OF UPDATE
ON CENTRAL.VPARTES
FOR EACH ROW
BEGIN
IF :OLD.SID_OFICINA = 'OF001' THEN
UPDATE OFICINA001.TPARTES
SET    
       SESTATUS       = :NEW.SESTATUS,
       ...
WHERE  1 = 1
AND SID_PARTE        = :NEW.SID_PARTE ;
ELSIF :OLD.SID_OFICINA = 'OF002' THEN 
UPDATE OFICINA002.TPARTES
SET    
       SESTATUS       = :NEW.SESTATUS,
       ...
WHERE  1 = 1
AND SID_PARTE        = :NEW.SID_PARTE ;
END IF;
END;
/

for the INSERT it would be kind of the same.

If you happen to use JHipster, to allow the usage of synonyms while passing the liquibase validation we need to add a hibernate property on our corresponding application-{profile}.yml or disable liquibase altogether.

spring:
    profiles:
        include: no-liquibase
...
    jpa:
        database-platform: org.hibernate.dialect.Oracle12cDialect
        database: ORACLE
        show-sql: false
        properties:
            ...
            hibernate.synonyms: true

sources:
http://stackoverflow.com/questions/6531729/updatable-view-oracle
http://stackoverflow.com/questions/8817253/jpa-entiy-on-synonym-instead-of-table

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 is like Heroku running on your own servers. This is pretty cool.

Normally, you should push your changes to the dokku repository and watch your code compile and run smoothly. But sometimes, the process of gathering dependencies and compiling your code takes to much time and processor, that sometimes gets rejected or it simply won’t compile on dokku server.
Probably, you already have a valid, tested, runnning jar in your development machine that you want to run on dokku, so how could you push this jar to the dokku server? well, let’s see…

In heroku, you have, among other options, the command

heroku deploy:jar

I don’t know of such a command for dokku[1]. but nevertheless you can deploy any jar(Many Java and JVM applications are packaged into a self-contained executable JAR file that includes application code, configuration and dependencies. These artifacts are often called “uberjars” or “fat jars”) with the following trick.

This article explains how to get a metabase runnable jar onto dokku. I’ve tried and it almost worked, the only really difference is that you have to create a java application skeleton with a maven archetype, and put your jar into version control.

so, first let’s create the skeleton for our java app deployment

mvn archetype:generate -DgroupId=com.sample -DartifactId=sample-jar-deploy -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

then run the following commands to configure and deploy to dokku

cd sample-jar-deploy
cp ~/Apps/sample-app/target/sample-app.jar .
echo "web: java -jar sample-app.jar" > Procfile
git init
git add .
git commit -m 'sample-app.jar version 0.1'
ssh dokku@where.your.dokku.is.com apps:create sample-app
git remote add dokku dokku@where.your.dokku.is.com:sample-app
git push dokku master

to upgrade your app

cp ~/Apps/sample-app/target/sample-app.jar .
git commit -am 'sample-app.jar version 0.2'
git push dokku master

Beware that this is definitively going to increase the size of the repository. This is only a temporary repository to have the jar deployed, your source and main repository should be in ~/Apps/sample-app/

to clean up and start over

cd sample-jar-deploy
rm -rf .git/
cp ~/Apps/sample-app/target/sample-app.jar .
git init
git add .
git commit -m 'sample-app.jar version 0.3'
ssh dokku@where.your.dokku.is.com apps:destroy sample-app
ssh dokku@where.your.dokku.is.com apps:create sample-app
git remote add dokku dokku@where.your.dokku.is.com:sample-app
git push dokku master

Of course you can deploy using buildpacker, dockerfile, docker image, and tarball based deploys which are documented.

Fuentes:
View story at Medium.com
http://dokku.viewdocs.io/dokku/
https://devcenter.heroku.com/articles/deploying-executable-jar-files
http://www.mkyong.com/maven/how-to-create-a-java-project-with-maven/

[1]:

 Hi, do anyone know if there's command like 'heroku deploy:jar' available for dokku
[16:09]  https://devcenter.heroku.com/articles/deploying-executable-jar-files#using-the-heroku-deploy-cli-plugin
[16:13]   no
[16:13]   we support buildpacker, dockerfile, docker image, and tarball based deploys
[16:14]   http://dokku.viewdocs.io/dokku/getting-started/installation/
[16:14]   sidebar on that page shows our deployment methods

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