Bula de Remédio

janeiro 3, 2016

Build an Unusual Project with Gradle

Filed under: Build, Gerencia de Configuração e Mudanças — jadsonjs @ 2:31 am

Gradle is the newest build systems that is became very popular in the Java world by its power and flexibility.

Gradle rather than having a configuration based on xml like Ant and Maven is written in Groovy a scripting language on the JVM. This gives us a pure programming language to develop our build on. Using Groovy Gradle can use any existing ant targets, Maven plug-ins or any Java classes making it a very powerful tool. It also uses the standard maven conventions so as long as everything is laid out like a maven project it can find everything without issue.


For any non-trivial projects it becomes mind-bending, and takes great care to ensure that complex builds are truly portable. Its imperative nature can lead to replication of configuration between builds



Maven takes the opposite approach and expects you to completely integrate with the Maven lifecycle. Experienced Ant users find this particularly jarring as Maven removes many of the freedoms you have in Ant. Maven configuration is very verbose, and if you want to do anything that is “not the Maven way” you have to write a plugin or use the hacky Ant integration.



Gradle combines good parts of both tools and builds on top of them with DSL and other improvements. It has Ant’s power and flexibility with Maven’s life-cycle and ease of use.


The end result is a tool that was released in 2012 and gained a lot of attention in a short period of time. For example, Google adopted Gradle as the default build tool for the Android OS.

Gradle DSL is designed to solve a specific problem: move software through its life cycle, from compilation through static analysis and testing until packaging and deployment.


Don’t know Gradle? Gradle Initial Tutorial

My presentation about Gradle


To show the Gradle power and flexibility, I needed to make a build for a legacy project that generated a EAR files with some JAR and WAR modules inside it. Very different from the Maven/Gradle default structure and some specific tasks that exist just in this project.

In this post, I put the Gradle script that I used for make the Continuos Integration of this project with Gradle.


The unusual project structure is show bellow:


Project Structure



—  src1

—  src2

—  src3

— app

|– project.ear

|– project.jar (compiled classes from src1, src2. src3)



|– web.xml



|– web.xml







And here is the Gradle script the make the build of this project. We are using the Gradle version 2.4.

The first step is include the required Gradle plugins.  Gradle has a War and EAR plugins that create War and Ear zip files. But with this plugins I could not create the EAR structure show above, so I used only the Java plugin and created the packing task manually.


Starting the build script include the required plugins:

/* A java plugin, with basic tasks to manager Java project */
apply plugin: 'java'

/* Plugin manager Eclipse IDE classpath */
apply plugin: 'eclipse'

/* Plugin to deploy the system using SSH */
apply plugin: "org.hidetake.ssh"

/* Plugin to version the SQL script using flyway tool */
apply plugin: 'org.flywaydb.flyway'


Now we need define some information about the application like the name and version. How we are using the Jenkins Continuos Integration Server to make the build of the system, we are passing some values from Jenkins Jobs parameter and reading this parameter with System.getProperty(“propertie_name”)


  /** Default task */
   defaultTasks 'build'

   /** Parametros para a build (serão definidos pelo jenkins ) */
   def application_name = 'myApp'; /*  Default name of the application*/
   /* Version of the application, pass by jenkins */
   def application_version = System.getProperty("application_version");



The next one is define some information about our source code properties:

/* Source and Target Java Version */
sourceCompatibility = 1.7
targetCompatibility = 1.7

/* Source code encoding */
compileJava.options.encoding = 'ISO-8859-1'
compileTestJava.options.encoding = 'ISO-8859-1'
compileJava.options.debugOptions.debugLevel = "source,lines,vars"
compileTestJava.options.debugOptions.debugLevel = "source,lines,vars"

/* Group of the output file */
group 'br.my_company'

/* System Version pass by parameter by jenkins */
version = application_version


Next step is define the structure of the project source folders:


sourceSets {
   /* Source Folder structure */
   main {
     java {
        srcDir 'src1'
        srcDir 'src2'
        srcDir 'src3'
     resources {
       srcDir 'src1'
       srcDir 'src2'
       srcDir 'src3'


Now I define the repositories where the Gradle will download the dependencies of the project. In other words, the JAR files used by our application:


/* declare the maven central repository */
repositories {

/* declare our own repository */
repositories {

 /* Declare an own internal Maven repository */
 maven {
   url "http://someURL.br/artifactory/architecture_dependencies"
    credentials {
      username '${artifactory_user}'
      password '${artifactory_password}'


In my case, I create 4 configuration that represent 4 types of dependence that we have is our project. For this configuration and for the default configuration of Gradle, I set all as a no transitive. To just download the Jars declared in this script and do not resolve transitive dependence (dependence of dependence) automatically.

configurations {
 compile {
 transitive = false
 transitive = false
 transitive = false
 transitive = false

 /* Internal dependence */
 internalLib {
 transitive = false
 /* external dependence */
 externalLib {
 transitive = false
 /* Jars files to copy to JBOSS deploy lib */
 deployLib {
   transitive = false
 /* Jar files that can not be copy to JBOSS deploy directory */
 noDeployLib {
   transitive = false
 // some configuration extends others
 deployLib.extendsFrom internalLib
 compile.extendsFrom deployLib, noDeployLib

// don't cache dynamic versions at all //
configurations.all {
 resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds'
// don't cache changing modules at all
configurations.all {
 resolutionStrategy.cacheChangingModulesFor 0, 'seconds'


Now between the dependencies closure we define the dependencies of our application:


dependencies {

  internalLib(group: 'br.my_company', name: 'comunsClasses', version: '1.4.11')

  externalLib(group: 'br.my_company', name: 'sharedResources', version: '1.6.8')

  deployLib(group: 'activation', name: 'activation', version: '1.1')
  deployLib(group: 'hibernate3', name: 'hibernate3', version: '3.2')

  noDeployLib(group: 'el-api', name: 'el-api', version: '6.0.20')
  noDeployLib(group: 'junit', name:'junit', version:'4.8')
  noDeployLib(group: 'mockito-all', name: 'mockito-all', version: '1.9.5')
  noDeployLib(group: 'org.powermock', name: 'powermock-core', version: '1.6.1')



Now we start to define the task used to create a EAR of the system.


At first, we define some variables with information about the project structure.


  def projectDirectory = "my_application_name"
  def secondWarDirectory = 'seconde_war_name'
  def earOutPut = "$buildDir/tmp/earOutput"
  def facedeName = "ejb_facede"
  def facedeDir = "app/"+projectDirectory+".ear/"+facedeName+".jar"



And then, I stated to create the tasks the will generated the parts of EAR final file. For each JAR or WAR file inside the EAR, I created a Gradle task.

The most of these tasks are tasks the create a zip file from a specific directory of the system project.


/* Create a JAR to the EJB module of the system, zipping the facade directory */
task createEJBFacedeJar(description : 'Create the JAR with de system EJB', type: Jar) << {
   archiveName = facedeName+".jar";
   from ("$facedeDir/")

/*Create the application_name.war file from the war directory */
task createWar(description : 'Created the Web aplication', type: War) << {
    // where the directory is located //
    from 'app/'+projectDirectory+'.ear/'+projectDirectory+'.war'
    baseName = application_name

/*Create a second war file, zip the directory if JSPs, CSS and JavaScript files */
task createSecondWar(description : 'Create the web aplication ', type: War) << {

  // where the directory is located //
  from 'app/'+projectDirectory+'.ear/'+secondWarDirectory+'.war'

  baseName = 'second_war_name'

/* Copy to temp directory of EAR the *.jars files and the META-INF directory */
task copyEarResouces(description : 'Copy EAR resources like META-INF') << {
 copy {
    delete "$earOutPut"
    from "app/"+projectDirectory+".ear/lib"
    into "$earOutPut/lib"
 copy {
    from "app/"+projectDirectory+".ear/META-INF"
    into "$earOutPut/META-INF"

/* Copy to temp directory the war file */
task copyWarFile (description : 'Copy WAR') << {
 copy {
    from "$buildDir/libs"
    into "$earOutPut"
    include "**/"+projectDirectory+"*.war"
    rename(/(.*)/, projectDirectory+'.war')

/* Copy to temp directory the second war file */
task copySecondWarFile (description : 'Copy WAR ') << {
 description = "Copy the War File to tmp output directory"
 copy {
   from "$buildDir/libs"
   into "$earOutPut"
   include "**/"+secondWarName+"*.war"
   rename(/(.*)/, secondWarName+'.war')

/* Copy to the temp directory the EJB jar file */
task copyEJBFacedeFile(description : 'Copy the JAR with the system EJB') << { 
   copy { 
     from "$buildDir/libs" 
     into "$earOutPut" 
     include "**/"+facedeName+".jar" 

/* Finally, zip the temp directory, creating the EAR zip file */
task earSystem(description : 'Create the EAR of system', type: Jar) << {
 archiveName = application_name+".ear";
 from ("$earOutPut/")


Here is an example of the power of the Gradle. I needed a specific task that probably few people need to do and is difficult to someone imagine to put this task as a default task in any build tool like Ant, Maven ou Gradle.

I needed to create a properties file inside the EAR file where this properties file should contain the version of some dependencies of my system and the release date. Some of this information are contained inside the own Gradle build script.

How with Gradle we can use programming languages structures like for and if and Groovy/Java API like FileWriter and Properties classes, this task became little bit easy.



task changeVersion (description : 'Change the information') << { 
   def props = new Properties() 
   def writer = new FileWriter(file('src/system_version.properties')) 
   try { 
     /* write all internal dependencies version */
     configurations.internalLib.dependencies.each { 
         dep -> props.setProperty(dep.name, dep.version); 
     /* write all external dependencies version*/
     configurations.externalLib.dependencies.each { 
         dep -> props.setProperty(dep.name, dep.version); 
     /* write the system version and release date*/
     props.setProperty("system", version); 
     props.setProperty("releaseDate", new Date().format('dd/MM/yyyy')); 
     props.store(writer, "System Version File"); 
   } finally { 


Now I just define the order of these tasks will run, to create the EAR file correctly:

assemble.dependsOn earSystem
earSystem.dependsOn copyWarFile, copySecondWarFile, copyEJBFacedeFile, copyJARFile
copyWarFile.dependsOn createWar
copySecondWarFile.dependsOn createSecondWar
copyEJBJARFile.dependsOn createEJBFacedeJar
copyJARFile.dependsOn jar
jar.dependsOn changeVersion


The build process is finish!!!

To run the tests, I create two tasks, one for each type of test. These tests are not call in the build, just when we call the specific task.

/* Task to run the unit tests for each build */
task unitTest(type: Test, dependsOn: testClasses) {

   include '**/AllUnitTests.*'
   exclude '**/AllIntegrationTests.*'

/* Task to run the integration tests just for especific builds */
task integrationTest(type: Test, dependsOn: testClasses) {

   include '**/AllIntegrationTests.*'
   exclude '**/AllUnitTests.*'


/* Configuration for all tests */
tasks.withType(Test) {

    /* Memory the will be used in the test */
    jvmArgs "-XX:MaxPermSize=1024m"
/* Disable test in the build, run the test only when call the specific task */
test {
   exclude '**/*'



But we also need that the project be compiled in our IDE. For this task, we can use the eclipse plugin:


eclipse {

 // Configure the file .classpath of eclipse
 pathVariables 'GRADLE_USER_HOME': file('${gradle.gradleUserHomeDir}')

 // where the eclipse will put the .class files
 classpath {
    defaultOutputDir = file('app/'+projectDirectory+'.ear/'+projectDirectory+'.jar')


/* Executa a task after configure the eclipse class path */
eclipseClasspath {


Using this plugin, all dependencies declared in the Gradle script will be automatically put in the .classpath eclipse file to make the build of the system inside Eclipse IDE. We don’t need configure the eclipse class path manually, nevermore.


In the dependencies closure we declared the dependencies of our system. But the dependence that the  Gradle need to run the build (in other words: where the Gradle will find the plugins), we need to declare inside the buidscript closure.

buildscript {
  repositories {
 repositories {
    maven {
       url "https://plugins.gradle.org/m2/"
 dependencies {
 classpath "org.jfrog.buildinfo:build-info-extractor-gradle:3.1.1"
 classpath "org.hidetake:gradle-ssh-plugin:1.1.3"
 classpath "org.flywaydb:flyway-gradle-plugin:3.2.1" /* Dependency of flyway */
 classpath "postgresql:postgresql:9.1-901.jdbc4" /* Postgres driver to flyway */


To automate the system deploy, you can use a org.hidetake.ssh plugin to copy by SSH the Jar, War or Ear of your system. This is a example of a ssh copy task:

task deploySystem (description: 'Deploy the system by SSH') <<{
 // properties read pass by jenkins
 def deploy_system_url = System.getProperty("servidorDeploy");
 def deploy_system_directory = System.getProperty("diretorioDeploy");
 def deploy_system_port = System.getProperty("portaDeploy");
 def deploy_system_user = System.getProperty("usuarioDeploy");
 def deploy_system_password = System.getProperty("passwordDeploy");

   /* Define the remote servers, you can use a forEach to run several */
   ssh.remotes {
      server1 {
          host = deploy_system_url
          port = new Integer(deploy_system_port)
          user = deploy_system_user
          password = deploy_system_password
          knownHosts = allowAnyHosts

  ssh.run {
    session(ssh.remotes.server1) {
       put from: "$buildDir/libs/*.ear", into: deploy_system_directory
       execute 'sudo service tomcat restart'

Database version is a important part of build when you want to eliminate manual deploys and use Continuos Delivery

Gradle has integration with the Flyway, a tool to  database migrations. The follow task make this integration:

/* apply the sqls and version the database
 * flywayMigrate Migrates the database
 * flywayClean Drops all objects in the configured schemas
 * flywayInfo Prints the details and status information about all the migrations
 * flywayValidate Validates the applied migrations against the ones available on the classpath
 * flywayBaseline Baselines an existing database, excluding all migrations up to and including baselineVersion
 * flywayRepair Repairs the metadata table
task applyScripts (description: 'Apply SQL scritps in the database') << {
 // properties get from jenkins
 def migrate_system_database_url =  System.getProperty("servidorMigracao"); 
 def migrate_system_database_name = System.getProperty("bancoDadosMigracao"); 
 def migrate_system_user =  System.getProperty("usuarioMigracao");
 def migrate_system_password = System.getProperty("passwordMigracao");

 flyway {
    user = migrate_system_user
    password = migrate_system_password
   // List are defined as comma-separated values
   // location of the SQLs scripts
   locations = ["filesystem:/$rootDir/../PROJECT_WITH_SCRIPTS/db/migration"]
   encoding = 'ISO-8859-1'
   println 'migrating: '+migrate_system_database_url+'/'+migrate_system_database_name


The Gradle Wrapper allow people to run Gradle without need to install it.

To use wrapper into your project you need to create the follow task in your build script:

/** Allow to run gradle without install */ 
task wrapper(type: Wrapper) { 
  gradleVersion = '2.4'

And, after that, run the wrapper task:

gradle -q wrapper 

After this the Gradle will generated “shell scripts” and Jar files in your project. You need to version this scripts in your project

Everyone can now download the scripts and Jars files and execute the build using these scripts:

./gradlew build


This script (gradlew.sh or gradlew.bat) will make the same thing of install Gradle and run grade -q build command.



This was a complete example of a Gradle build script used to make a Continuos Integration process in a complex real legacy project that use an unusual structure.

This exemple showed the power and flexibility of Gradle that let us decide step by step how the build will be made. Sometimes you can stop a company to change the entire system structure to fit in the maven way to do things. Gradle helped us a lot.

But if you have new projects you can also use Gradle, without use so much configuration to build fast forward your project.

Because of this flexibility and live philosophy, people are switching Maven by Gradle as build system.



julho 31, 2014

Generating PDF file from HTML in JAVA

Filed under: Código e Algoritmos — jadsonjs @ 11:06 pm

After spend hours trying to generate a simple PDF file from a HTML Java String, I found this solution:


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public ByteArrayOutputStream convertHtml2Pdf(String text) throws IOException, DocumentException{

   ByteArrayOutputStream outputStreamTemp = new ByteArrayOutputStream();

   Document document = new Document();

   PdfWriter writer = PdfWriter.getInstance(document, outputStreamTemp);


   XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(text.getBytes()));


   return outputStreamTemp;

Instead a temporary ByteArrayOutputStream you can use direct files:


new FileOutputStream("file.pdf") -> ByteArrayOutputStream outputStreamTemp;

new FileInputStream("index.html"); -> new ByteArrayInputStream(text.getBytes());

Jars you need:


Simple like this.


novembro 10, 2013

Dicas para Comprar um Imóvel na Planta

Filed under: Financeiro — jadsonjs @ 6:04 pm

Versão 1.2


Esse artigos contém dicas para quem pretende comprar um imóvel baseado na minha própria experiência.

Para a Compra

A primeira coisa a ser tomar cuidado, e vale para tudo que você for comparar.  Nunca acredite na palavra do vendedor, nesse caso o corretor de imóveis. Nenhum vendedor será honesto com você, toda pergunta que você fizer ele vai dizer que você tem direito e vai tentar esconder os defeitos existentes no projeto.

Então antes de tudo peça para ler o contrato com a construtora e o memorial descrito da obra. O memorial descrito é o documento que diz tudo que  vai ser entregue com a obra. Se não tiver no memorial descritivo, você não terá direito de cobrar depois.

Tudo que o vendedor prometer, verifique se está no memorial descritivo e grife isso. Se não tiver, peça para adicionar por escrito.  Não assine nada antes de ler o contrato e o memorial descritivo por inteiro. Grife as principais partes para você lembrar de cobrar depois, na entrega.

 Peça as plantas elétrica, hidráulica, de esgoto e instalações de telecom antes de assinar o contrato, verifique o espaço e a disposições da coisas, para sabe que móveis e eletrodomésticos você poderá comparar e onde eles poderão ficar.

Cuidado com a taxa de corretagem. Se você não contratou diretamente uma corretora para fazer a compra para você, você não deve pagar nada a ela, é ilegal, quem devem pagar é a construtora que contratou a corretora para vender o imóvel. Em muitos contratos vem uma cláusula: “Eu aceito pagar a taxa de corretagem…”.  Essa cláusula é abusiva, não pague!


Coisas para prestar atenção que a maioria esquece:

Ao comprar imóveis na planta tome cuidado com a disposição dos cômodos. Por exemplo, um apartamento de 2 quartos pode ser mais confortável que um maior de 3 quartos. Isso porque a adição de um quarto a mais na planta, sem o aumento equivalente na metragem quadrada do imóvel, pode deixar apartamento maior mais apertado e desconfortável. Isso é o único ponto que vê o decorado pode te ajudar.

As vagas das garagens são cobertas ? Se não, prepare dinheiro para cobrir depois.

Caso você tenha direito a mais de uma vaga na garagem, elas são paralelas? Geralmente nos imóveis populares ou para a classe média, se tiver direito a mais de uma, elas serão uma atrás da outra, que dá mais trabalho quando você quer sair no carro que está na vaga da frente, mas economiza espaço para o condomínio.

A energia, água e gás são individuais? Isso é muito importante para não pagar o que os outros consumiram. Veja se isso está escrito e se já está tudo pronto ao receber ou você terá que comprar ainda alguma coisa para individualizar. Ocorre que na hora da compara eles dizem que tudo é individual, mas na verdade é só a infraestrutura que vem pronta para ser individualizada, na hora de receber você percebe que terá ainda que comparar aparelhos para que realmente seja individual.

Guarde dinheiro para os custos da ligação de água, energia, telefone, TV a internet, normalmente nada disso vem instalado e pronto para usar.

O apartamento tem alguma preparação acústica?

Os corredores e portas foram preparados para passagem de cadeira de rodas e pessoas com deficiência física? Não necessariamente precisa ser um apartamento adaptado, mas por exemplo, geralmente as portas são estreitas demais para passar uma simples cadeira de rodas. O que implica em mais gastos futuros. Um dia você ou alguém da sua família pode precisar.

A área onde o imóvel está localizado imunda quando chove muito forte? Muitos apartamentos são construídos em áreas que inundam no período de chuvas.

Peça a planta baixa, elétrica e hidráulica do imóvel.

Verifique se há tomadas em quantidade e disposição suficiente para os aparelhos que você deseja comprar e na posição que você deseja colocar.

Quer usar uma coifa para ficar chique igual aos apartamento decorados que você vê por ai? Verifique se a cozinha vem com o duto de exaustão.

O gás é encanado? Verifique onde vai ficar a saída de gás nas plantas do imóvel. Para saber em que posição será possível colocar o fogão.

Verifique na planta o espaço deixado para o fogão, geladeira, cama, etc. Muitos apartamento, principalmente os pequenos, são feitos para caber apenas fogões 4 bocas, geladeiras e camas pequenas. Não fique sonhando com aquela geladeira side by side e aquela cama king size porque, se você não olhou isso na plantas antes, quando você receber, perceberá que não terá espaço para colocar.



Cuidado com o decorado:

Apartamento decorado é um truque usado por arquitetos/decoradores para fazer uma maquiagem e enganar os bestas. Acho que eles até devem pagar uma disciplina disso na faculdade. “Truques para enganar os bestas”, ou “Ilusão de ótica 1” ou “Ilusão de ótica 2”.

Então se possível, nem visite-o. Você só vai criar expectativas que não irá receber. Se quiser ver a decoração para pegar dicas, a internet está cheio de fotos e dicas sobre isso.

No decorado eles não vão seguir o que está no memorial descritivo. Então vão colocar tudo do bom e do melhor que você não irá receber. E não adianta reclamar depois, porque não está previsto no documento que você assinou. A não ser que você esteja comprando um imóvel de luxo, e tudo do bom e do melhor esteja explicitamente descrito no memorial descritivo.

Um exemplo de diferenças que podem ser encontradas entre o decorado e o que foi realmente entregue:


Sala de estar



O decorado serve no máximo para você ter uma ideia de espaço do seu apartamento. Mas você tem que tomar cuidado para não ser iludido. O decorado vai está cheio de espelhos por tudo que é lugar, e os móveis vão está posicionados da forma que você tenha a ilusão que ele é maior do que realmente é.

Se for possível, para não criar falsas expectativas e você saber realmente o que irá receber instalado no imóvel, peça para que o imóvel venha sem piso, sem louças, sem pias, sem torneiras, sem nada. Algumas construtoras permitem que você compare isso por fora e elas mesmas instalam. Desde que você avise dentro de um determinado prazo.

Então compre por fora e peça para instalar ou você instala depois que receber. Logicamente peça desconto no preço do imóvel, porque você que estará comprando peças que já estão embutidas no preço.

Isso garante que você tenha o controle do que será instalado no apartamento. O memorial descritivo nunca é preciso nesse aspecto, geralmente vem dizendo apenas que poderão ser instaladas peças das marcas e modelos X, Y ou Z, mas você nunca sabe, até entrar pela primeira vez no imóvel, quais marcas e modelos serão realmente instalados.  Normalmente o mais barato dentre as possibilidades existentes no memorial descritivo, porque a construtora visa a maior lucro possível.

Ou possibilidade é negociar para mudar o memorial descritivo especificando qual a marca e modelo que será instalado. Sempre por escrito e assinado, é sempre bom lembrar: não confie apenas na palavra de quem está te vendendo.

Em muitos casos as posições em que os móveis e aparelhos eletrônicos são colocados no apartamento decorado não estarão disponíveis no apartamento real que você receberá. Seja porque não tem tomada, existirá um ralo em baixo que não poderá ser tampado, ou não haverá espaço. Então, gostou da posição da geladeira no apartamento decorado? Verifique se na planta baixa do apartamento terá espaço e tomada para ela lá.

Não confie no tamanho das coisas no apartamento decorado, as vezes eles movem uma parede ou pia de lugar para caber uma geladeira, fogão ou cama grande. Verifique o tamanho real dos espaços do imóvel na planta baixa.


Crédito Imobiliário


Um coisa importante a se saber. Financiar um imóvel não é igual a um financiamento de um carro ou um crediário em uma loja. Que você aplica o juros, divide pelo número de prestações e tem o valor fixo da parcela de cada mês.

Tanto no financiamento com o banco quanto no “financiamento” que você faz com a construtora até receber o imóvel, as parcelas e o saldo devedor nunca são fixos. Sofrem reajustes a todo tempo.

A única diferença que não nos permite chamar as parcelas que você paga a construtora de financiamento é que eles não podem cobrar juros, pois nada foi entregue ainda, e sim uma taxa de correção chamada INCC[1]. Que é na média ligeiramente menor que os juros, mas na prática  funciona como um juros.

O corretor vai te vender o imóvel, você tendo dinheiro ou não para pagar. Isso não é problemas dele nem da construtora. Até porque se você desistir depois de comprado é melhor para eles, porque eles ficam com o apartamento e cobram uma taxa de desistência de uns 20% do valor pago até o momento.

Então nunca olhe o valor da prestação. Na prática é o valor que você quiser, se quiser pagar 1 real por mês você paga.

Um boa forma de você saber se pode pagar a imóvel é sempre fazer esse calculo:

Até a entrega o valor devido será corrigido pelo INCC. Em Outubro de 2013 o valor do INCC foi de 0,33%, então se você comprou um imóvel de 300.000,00, dando apenas 50.000,00 de entrada (16,66% de entrada) e ficando um saldo devedor de 250.000,00 com 0.33% de correção dá o valor de 825,00.  Você tem que ter uma prestação acima de 825,00 para está efetivamente pagando o imóvel, se você nesse mês pagar uma prestação de apenas 800,00. No mês seguinte você estará devendo 250.025,00. Mais do que o valor inicial, virando uma bola de neve.

Isso no melhor caso, no mês de julho o INCC foi de 1,96%,  então o valor da correção foi de 4.900 reais. Você teria que pagar pelo menos 5.000 reais de prestação para a dívida não virar bola de neve. A média de 2013 o INCC foi 0,75%, que dá uma correção de 1875,00 reais. Ou seja, se você der apenas 50.000,00 como entrada,  num imóvel que custa 300.000,00, a prestação mínima deveria ser de 2.000,00 por mês. Apesar que a construtora não está nem ai para isso e iludir você com prestações de 500,00 ou 1.000,00.

Isso vale para o financiamento com o banco também. Veja quanto você pagar de juros e quanto realmente é abatido do saldo devedor todo mês. Se você um dia quiser quitar o financiamento é importante que o valor da prestação seja maior que os juros ou correção.

Na minha opinião, de preferência a prestação deveria ser o dobro do juros/correção cobrada. No caso acima citado, 4.000,00 por mês. Multo alta, considerando que a média da renda do brasileiro gira em trono de 1.600 reais e que você deve gastar no máximo 30% da sua renda com a prestação para não ficar apertado, sua renda deveria ser de 13,333, 33 reais.

Ou seja, tem que ter uma renda muito alta. O ideal era que a entrada do imóvel fosse maior, pelo menos 50% do valor do imóvel. R$ 150.000,00

Sobre crédito imobiliário, tipos de financiamento etc, existe um bom artigo na revista Dinheiro$Direitos  número 13 de abril de 2008 [2].

Resumidamente, no financiamento você deve olhar o CET (custo efetivo total), nunca o valor dos juros, pois um banco pode cobrar juros menores, mas embutir outras taxas que encareçam o financiamento.

E prefira o sistema SAC em vez do PRICE, pois o custo final é menor. Não olhe apenas o valor inicial as prestações.

Taxas e Mais Taxas

Outro artigo muito bom intitulado “Prepare o bolso para Bancar as Taxas do Imóvel”[3], descreve várias taxas que geralmente ninguém leva em conta na hora da compra. Trecho retirado de lá:

“Você passa anos juntando dinheiro para comprar ou dar entrada no imóvel dos seus sonhos, até que, na hora da compra, percebe que faltou verba para os gastos com cartório e impostos. Parece um pesadelo, mas essa situação é comum entre os proprietários virgens, que vão realizar o negócio pela primeira vez. Muitos, inclusive, desistem da compra por causa das tarifas ou mesmo têm que recorrer a empréstimos bancários para conseguir quitar as obrigações e conseguir finalizar a aquisição ou dar entrada no financiamento. Para evitar surpresas desagradáveis, o indicado é reservar não apenas 5%, mas entre 6% e 10% do valor do imóvel para a autenticação de documentos, tarifas cartorárias, despachantes e taxas de financiamento.”

Vejam algumas taxas descritas no artigo, um absurdo, é Brasil:

“Nos cartórios, além da escritura e do registro, que podem chegar a custar R$ 3,4 mil e R$ 2.267,18 respectivamente, existem ainda a taxa de registro do contrato de compra e venda, que é opcional, mas pode ter o mesmo preço da lavratura da escritura, ou seja, até R$ 3.400

Outra taxa comum é paga no certificado de ônus imobiliário, que custa cerca de R$ 30 a folha.

No caso de imóveis financiados por alguma instituição bancária, mais gastos surgem. A Caixa, por exemplo, cobra R$ 40 na taxa de cadastro e até 1% do valor do bem na Taxa de Avaliação de Bens Recebidos em Garantia. “Essa taxa pode ser de 1% no caso de financiamentos por FGTS e de R$ 800 nos financiamentos através do SBPE, que usa fundos da poupança”, explicou a gerente regional de Habitação da Caixa, Eveline Martins

Taxa de escrituração imobiliária
É paga no Cartório de Registro de Imóveis (responsável por lavrar a escritura de compra e venda) de acordo com a faixa de preço do imóvel. No caso de um imóvel de R$ 100 mil, a taxa cobrada, por exemplo, é de R$ 1.627,23

Taxa de registro do imóvel
É paga no cartório no momento do registro da compra no seu nome de acordo com a faixa de preço de imóvel. Se o imóvel custa R$ 100 mil, a taxa cobrada será R$ 870, 71.

Tarifas bancárias no caso de financiamento. Na compra financiada pela Caixa, a taxa de escrituração não precisa ser paga, pois o contrato bancário tem força de escritura pública. Porém, outras taxas são cobradas como:

Taxa de Cadastro. Devida por operação/contrato no ato de assinatura do contrato, no valor da tabela de tarifas da Caixa, sendo cobrada uma única taxa para os proponentes e uma outra para os vendedores, independente do número de participantes: R$ 30,00.

Taxa de Avaliação de Bens
Recebidos em Garantia a ser paga pelo proponente, à razão de 1% sobre o valor do financiamento, no ato de assinatura do contrato (para compra de imóvel pronto)

Imposto sobre transmissão de bens imobiliários (ITBI)
É pago à prefeitura e custa em média 2,5 % do valor venal do imóvel.


Guarde dinheiro para isso, não pense que só porque a prestação do banco coube no seu bolso que está tudo resolvido.

Hora de Receber


É preciso fazer uma vistoria no momento do recebimento do apartamento para verificar defeitos aparentes. Vá com roupas confortáveis e descansado, uma inspeção minuciosa e bem feita vai demorar 2 ou 3 horas. Normalmente eles reservam 1h para cada pessoa, não se importe com isso. Leve outra pessoa para ver o que você pode deixar passar. No final desse artigo existem um checklist como sugestões de coisas que devem ser verificadas. Leve um checklist com você.

Existem vários outras na internet bem como vídeo no http://http://www.youtube.com  ensinando a fazer a vistoria.


No momento da entrega será instalado o condomínio. Para isso será necessário eleger  o síndico o sub síndico os membros do conselho fiscal e a empresa que gerenciar o condomínio. Principalmente se for uma condomínio grande, é necessário que se tenha uma empresa com software e processos bem definidos de como se administrar um condomínio. Não dá mais para ser um trabalhos de amadores anotando tudo um folhas de papel.

Ser síndico dá muito trabalho, então é indicado eleger pessoas que tenham tempo e experiência para função. Por exemplo aposentados que já tenham sido síndicos em outros condomínios.

É muito importante que se tenha membros do conselho fiscal exigentes. Para que o síndico não se alie com a empresa administradora e realizem desfalques no condomínio. Porque se não sobrará para você pagar depois, lembre-se aqui é Brasil. Todo mundo faz de tudo para passar a perna em você.

Para a instalação do condomínio será necessário uma taxa para comparar materiais que não estão previstos no memorial descritivo, como itens de consumo e o fundo de reserva para o condomínio. Normalmente é um valor pequeno, um pouco maior que uma parcela do condomínio. Guarde dinheiro para isso também!.


CheckList para a Vistoria do Apartamento

O que levar?

Papel e caneta para anotação

Máquina fotográfica para registrar todos os problemas encontrados

Trena, fita métrica, régua e espelho pequeno

Lâmpada para teste dos bocais
 (normalmente eles já fornecem o bocal com lâmpada para testes)

Aparelho para teste de tomadas (normalmente eles já fornecem uma tomada com lâmpada para testes)

Balde e Rodo para teste de escoamento e vedação da parte hidráulica. Leve o rodo senão vai ficar água empossada se você derramar com o balde.

E esse checklist!


Verificar a Pintura:

• Das paredes
   [ ] [ ]

• Da guarnição das portas   [ ] [ ]

• Em cima e embaixo das portas (use um espelho para consegui ver)   [ ] [ ]

• Próxima as ferragens e maçanetas   [ ] [ ]

• Ao redor dos acabamentos de elétrica
   [ ] [ ]

• Ao redor dos espelhos das tomadas   [ ] [ ]

Verificar o Nivelamento:

• Das paredes   [ ] [ ]

• Dos revestimentos da parede   [ ] [ ]

• Do piso   [ ] [ ]

Verificar o Revestimento Cerâmico:

• se está sem lascados ou riscos   [ ] [ ]

• se estão ocos   [ ] [ ]

Verificar as Louças:

• Se não tem defeitos como lascados, riscos ou manchas   [ ] [ ]

• Se estão bem vedadas nos cantos e nos rejuntes  [ ] [ ]

Verificar os Metais:

• Se as torneiras e registros não tem riscos ou manchas de produto químico  [ ] [ ]

Verificar as Esquadrias e Persianas:

• Se estão bem vedadas com silicone  [ ] [ ]

• Se estão fechando e travando perfeitamente [ ] [ ]

Verificar os Vidros:

• Se não estão riscados, trincados ou quebrados  [ ] [ ]

Verificar a Parte elétrica:

• Se o quadro está identificado com adesivos [ ] [ ]

• Usando lâmpadas teste se todos os bocais funcionam e todos os interruptores [ ] [ ]

• Teste a campainha [ ] [ ]

• Teste o interfone [ ] [ ]

• Verifique se os pontos de gás estão vedados [ ] [ ]

Verificar a Parte Hidráulica:

• Abra todas as torneiras, deixe a água correndo um tempo
 e veja se há vazamentos (passando a mão seca em baixo das pias) [ ] [ ]

• Faça o mesmo com os chuveiros e veja se tem vazamentos [ ] [ ]

• Fechamento dos registros com as torneiras abertas
 [ ] [ ]

• Veja se a altura do cano do chuveiro está ok, não pode ser muito perto do teto [ ] [ ]

• Descargas dos vasos sanitários [ ] [ ]

• Caimento e escoamento na varanda, lavanderia e banheiros. Jogue um balde de água no chão e veja se a água escorre em direção ao ralo, fica empossada, ou no pior caso, escorre em direção oposta onde fica o ralo. [ ] [ ]

• A área do banheiro onde tem o vaso sanitário é impermeabilizada? [ ] [ ]

Verificar as Medidas:

• das paredes e portas [ ] [ ]

• metragem quadrada do imóvel. [ ] [ ]

Sempre no contrato ele colocam que pode ter 5% de margem de erro do que foi vendido, e por coincidência todos os cômodos tem sempre é 5% a menos, nunca a mais. Ou seja, você vai receber um apartamento 5% menos do que comprou.

Verificar as áreas de Lazer:

• confira tudo que está no memorial descritivo com o que foi entregue  [ ] [ ]

outubro 7, 2013

Creating zip files with Java

Filed under: Uncategorized — jadsonjs @ 10:14 pm

Jadson José dos Santos – jadsonjs@gmail.com

The Java API has the java.util.zip package that allows compact several files in a unique zip file.
This functionality is very useful when you need to send to the user several files in a unique web application request. Since is only possible send one file by request and there is not a way to create several directories on the client side to organized this information.


File Generation:
The first thing is creating a temporary file output, since we don’t need to save a file in the server side. You can do this on Java using the ByteArrayOutputScream class. So you can instantiate a ZipOutputStream class passing this output stream.

ByteArrayOutputStream outputStreamZipFile = new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(outputStreamZipFile);

To organize many files, can be interesting create some directories in the zip file. To do this it is necessary just added “ZipEntries” with the “/” character. Everything that ends up with “/” is considered a directory to the Java Zip API.

String directoryName = directory+"/";
zout.putNextEntry(new ZipEntry(directoryName));

The below code create a temp text file. You can use any Java method that you know to create files, for example the File class.
The only thing you should know is that you will need to generate a byte array in the end. So, use the ByteArrayOutputScream class again is a good choose.

ByteArrayOutputStream tempFileOutput = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(tempFileOutput));

Create a new “ZipEntry” object starting with the directory name and write the file output stream. It will do the file be created inside of the directory.

ZipEntry zipEntryFile  = new ZipEntry(directoryName +"file.txt");
zout.putNextEntry(zipEntryFile );
zout.write(tempFileOutput.toByteArray());  // write the data into ZipEntry
zout.closeEntry();                                               // create a new file inside zip file

You can create several “ZipEntry”, each “ZipEntry” will be a file inside the zip file.
To finish, close the ZipOutputStream and return the stream object that was used to create the zip file.

return outputStreamZipFile;


Send the file to the user by web browser:
It is possible to send the zip file to the web browser using the HttpServletResponse object and the ByteArrayOutputStream object that were used to create the ZipOutputStream object.

HttpServletResponse response = getCurrentResponse();

ByteArrayOutputStream outputStreamZipFile = genereteZipFile();

response.setContentType("Content-Type: application/zip;");
response.addHeader("Content-Disposition", "attachment; filename=output.zip");

For more details about how choose the zip compression model, API methods, among other things, consult:
http://www.devmedia.com.br/criando-um-arquivo-compactado-zip/2293 (in Portuguese)
http://www.guj.com.br/articles/181 (in Portuguese)

maio 25, 2013

Usando o Mac OS

Filed under: Uncategorized — jadsonjs @ 3:26 am

Atalhos do Teclados:

Copiar: Command ⌘ + C

Colar: Command ⌘ + V

Mover:  Copiar: Command ⌘ + C    ->   Option ⌥  +  Command ⌘ + V

Mover Item para o Lixo:   Command ⌘ + Delete

Tecla Delete do PC:  fn + Delete

Print Screen Tela completa:  Command ⌘ + Shift + 3

Print Screen Selecionando:  Command ⌘ + Shift + 4



Visualizar arquivos ocultos:

defaults write com.apple.finder AppleShowAllFiles -bool true
reiniciar o finder


Não visualizar arquivos ocultos:

defaults write com.apple.finder AppleShowAllFiles -bool false
reiniciar o finder

Abrir arquivo baixado na Internet: control + botão direito + abrir   (isso pula a verificação de segurança do Gatekeeper)




Configurar uma variável de ambiente : PATH=$PATH:/Users/… /../…/seu_diretorio

Executando um arquivo shell script:  sh nome_do_arquivo.sh


Conditional Execution: A Pattern for the Implementation of Fine-Grained Variabilities in Software Product Lines

Filed under: Padrões de Projeto — jadsonjs @ 2:28 am

Jadson Santos1,2, Gleydson Lima1,2, Uirá Kulesza1 Demóstenes Sena1, Felipe Pinto1, Jalerson Lima1 Alexandre Vianna1, David Pereira2, Victor Fernandes2

1 Department of Informatics and Applied Mathematics (DIMAP) – Federal University of Rio Grande do Norte (UFRN) – Natal – RN – Brazil

2Informatic Superintendence (SINFO) – Federal University of Rio Grande do Norte (UFRN) – Natal – RN – Brazil

jadson@info.ufrn.br, gleydson@info.ufrn.br, uira@dimap.ufrn.br, demostenes.sena@ifrn.edu.br, felipe.pinto@ifrn.edu.br, jalerson.lima@ifrn.edu.br, strapacao@gmail.com, david@info.ufrn.br, victorhcf@gmail.com

Abstract. This paper presents the Conditional Execution design pattern that aims to help the implementation of fine-grained variabilities in the context of software product lines of information systems. The pattern has been used successfully in three product lines of web information systems developed by Informatic Superintendence (SINFO) at Federal University of Rio Grande do Norte.

1. Intention

The Conditional Execution design pattern contributes to the implementation of fine-grained variabilities in the context of software product lines (SPL) [Clements and Northrop 2001] [Czarnecki and Eisenecker 2000] [Weiss 1999] of information systems. It provides support to the modularization of a certain variability located in one or more modules to values assigned to configurations parameters, allowing its activation (or deactivation) dynamically in the system.

2. Example

In order to illustrate the need for the usage of the pattern, we present examples from a Library Management module of a software product line of an academic information system. We use the punishment functionality for users who return late borrowed books. This functionality defines a variability that determines the kinds of punishment, which can be: (i) a payment in cash or (ii) a suspension for a period of time without to make new loans.

During the execution of the system, which represents a product (instance) of the SPL, the decision for execution of such punishment variability can happen several times, for example, during the execution of a new loan, returning a book or printing a bill for payment. The variability code is also spread among the system layers, from the calculation of the amounts of punishment in the business layer to the user visualization of loan functionalities in GUI layer. In some cases, the system manager can provide a

“period of forgiving” during which the users do not receive punishment, even if they return the material overdue. All variabilities related to the punishment feature must be deactivated from the system and then being re-activated immediately after the system manager request.

Listing 1 shows the code of the ReturnLoanProcessor class from business layer containing the functionality “return of a book loan” without the punishment variability. We want to create a variation point inside the core conditional statement that verifies if the return of the book is delayed. It is noticed that the code that creates a suspension is intertwined with business code that verifies the permission of the operator (library employee who performs the loan), updating the data to commit the loan and sending e-mail information to the user about the book return.


Listing 1: Example of fine-grained variability in business layer

Software product lines of medium and large scale with a large number of features, tend to have fine-grained variabilities [Kästner, Apel and Kuhlemann 2008] that are intertwined with the implementations of other common and variable features.

It is necessary to implement the variability of execution the punishment feature in the example in Listing 1 in a way that, depending on the type of punishment that is currently active, the code that implements such variability is executed, creating the correct punishment for the user, instead always create a suspension.

The decision for the execution of the variability need be codified to allow its dynamic change, reflecting if the punishment variability is currently active or not. In addition, it is also need the introduction of the variability implementation inside of classes of the business layer. In Listing 1, for example, the punishment variability must be implemented using another conditional statement (“if”) that determines its execution.

Finally, another requirement is that the proposed solution to implement the punishment variability can be used in other modules of the system, eventually implemented using other technologies. Listing 2 shows, for example, a Java Server Faces (JSF) web page from the same system, which implements a menu with the user options related to the functionalities of the book loan. The item “Print Bill for Pay Library Fines” should be visible to users only if the variability of fine is enabled.


Listing 2: Example of fine-grained variability in view layer.

Object-oriented (OO) solutions such as design patterns [Gamma et al 1995] can contribute to the modularization of SPL variabilities in information systems by providing flexible structures to implement optional and alternatives features, which may be activated depending on the desired behavior in the product. For example, the State or Strategy [Gamma et al 1995] design patterns can be used to implement alternative variabilities, such as the example shown in Listing 1, which involves choosing one among a set of algorithms or possible states.

Although the adoption of traditional design patterns can help the modularization of SPL variabilities in information systems, the decision to instantiate or execute such variability may depend on many other parameters configured from the SPL domain. These parameters can be available during the process of derivation of the product (configuration parameters of the product) or only during its execution.

There are other modularization techniques that can be used in the implementation of fine-grained variability of information systems, such as aspect- oriented programming and conditional compilation. Each one of them faces difficulties when used in this context. Aspect-oriented programming (AOP) enables the modularization of such variabilities. However, the implementation of fine-grained variabilities is usually strongly coupled with the business code where it is located. Because of that, the use of aspects requires to expose all parameters used by the variability, which demands the codification of complex pointcuts [Kästner, Apel and Kuhlemann 2008]. Furthermore, in the context of the development of information

systems in the industry, it is not common to find software engineers who have advanced knowledge for using such technique.

The Conditional Compilation is another technique that can be used for implementing fine-grained variabilities. This technique works by defining a set of pre- processor directives in the source code, which indicate the inclusion of a fragment of code on the product of a SPL. However, this technique provides a series of limitations compared to other existing ones: (i) it is possible to define only boolean parameters when specifying the variability, and (ii) all the variabilities need to be addressed and solved during the compilation of the system, there is no support for the definition of variabilities, whose execution can be decided during the system execution.

3. Context

Nowadays there is a great demand in the industry for the customization of information software systems already developed for a given institution, in order to adapt those systems to be used in environments from other institutions. One of the motivations for such scenario is to increase productivity and quality of development of new information systems through the reuse of design and code of previously developed systems.

In this context, software engineering approaches to the development of software product lines (SPL) emerge as a promising proposal. A SPL can be seen as a family of systems that maintains: (i) a set of common features for all members of the family, known as similarities; and (ii) a set of variable features that changes based on specific needs of a SPL family member (product), called variabilities. A feature represents a functionality or property of SPLs that is used to capture their similarities and distinguish their variabilities.

The development process of SPLs involves not only the identification and modeling of their similarities and variabilities, but also the definition of a flexible architecture and the choice of adequate implementation techniques to modularize the SPL variabilities.


4. Problem

The Conditional Execution pattern proposes to address the following question: How to implement fine-grained variabilities in information system product lines in order to allow dynamic product configuration, without causing major changes impacts on architecture designed, keeping the performance expected by the system and being flexible enough to be implemented by all its modules and/or layers?

The following forces emerge from this problem:

(1) Dynamic Configuration: The variability choice should be performed dynamically, thus giving more flexibility to the SPL customization.

(2) Low Impact: The implementation of the variability should not require substantial changes on the SPL structure .

(3) Fine Granularity and Crosscutting: The variability can appear in any layer or piece of code, being fine-grained and/or crosscutting.

(4) Performance: The solution should run with low overhead for the system.

5. Solution

The pattern proposes to map each identified variability to a configuration parameter, which allows defining if the variation will be performed at runtime according to the parameter value.

The parameters are stored in a persistent repository, which allows easily reading and updating their values. A component is concerned in retrieving the parameter values in a transparent and efficient way, so it can instantiate the variability code to be executed based on these values.

The proposed solution is a combination of conditional statements “ifs” with configuration parameters of the system. Thus, it can decide which variability will be present in a particular product by adding or removing variabilities at runtime without keeping this decision hardcoded.

6. Structure

The Conditional Execution pattern consists of four main participants, which are illustrated in Figure 1:

Structure Diagram

Figure 1: Conditional Execution pattern structure.

6.1 Target Classes

It represents the system components where variabilities happen. The execution of the variability code depends on the configuration of the system parameters values. In the context of web information systems, Target Classes may be in any layer of the application, includying dynamic HTML content pages.

6.2 Variability Implementation

The code that modularizes the variability is located within the Target Classes. It usually consists on: (i) a direct implementation of variability code inside a Target Class; or (ii) a call to a component that implements the variability. The execution of this snippet is decided by the Execution Manager.

6.3 Execution Manager

The Execution Manager is the central element of the pattern. It determines if certain SPL variability will be executed or not based on configuration parameters from the system. The main tasks of this element are: (i) to get the parameters values from the repository as efficiently and transparently as possible; and (ii) to determine the execution of the variabilities associated with the retrieved parameters on Target Classes. Execution Manager contains the decision logic to determine if the variability is performed, removing this responsibility from the Target Classes. It provides access to configuration parameters, allowing the runtime adaptation of the variability. Finally, the Execution Manager must also provide mechanisms to optimize and minimize access to the repository, and it must maintain the parameters values synchronized with the values stored in the repository.

6.4 Parameters Repository

The Parameters Repository is responsible to store the parameters values used during the conditional execution. It allows storing and updating the parameters values during the application execution. It is fundamental that the retrieving of the parameter values is not costly for the system performance. Database systems or local files are examples of technologies that can be used as a parameter repository.

7. Dynamic

The following scenario defines the behavior of the Conditional Execution pattern during the runtime execution of variabilities.

Scenario 1: Variability Execution

An instance of the Target Class calls the Execution Manager to determine if the variability will be performed. The Execution Manager retrieves the parameter value by calling the Parameters Repository. After that, the Execution Manager indicates to the Target Class if the Variability Implementation must be executed or not. Figure 2 shows a sequence diagram that illustrates this scenario.

Dinâmica do Padrão Execucao Condicional

Figure 2: Dynamic of the Conditional Execution pattern.

8. Consequences

The Conditional Execution pattern brings the following benefits:

  • Simplicity. It simplifies the implementation and customization of fine-grained variabilities by allowing the extraction or introduction of SPL variabilities in existing legacy information systems.
  • Load-time or runtime customization. Variabilities can be configured at load or execution time. Changes in the system business rules, for example, that demands the addition or removal of variabilities may be performed by the software engineers without the need to recompile the system, such as using techniques like Conditional Compilation.
  • Preventing compilations issues. All variabilities code are present in the SPL products, the pattern eliminates the possibility of generating compilation errors during the product derivation process compared to the Conditional Compilation technique [Kästner and Apel 2009].
  • Reducing code complexity. It avoids the implementation of aspects with complex pointcuts that need exposing several parameters. It allows introducing variability code based on parameter values that can be easily implementing in any mainstream programming languages.On the other hand, Conditional Execution pattern has the following drawbacks:

• Poor variability modularization. When compared to other techniques such as aspect-oriented programming, the Conditional Execution pattern does not provide an adequate modularization, because it does not promote the separated and localized implementation of fine-grained variability. However, the usage and adaptation of virtual separation of concerns (VSoC) tools [Kästner, Apel and Kuhlemann 2008] can help to overcome this deficiency.

• Late detection of variability correct configuration. Because the Conditional Execution pattern is an implementation technique that enables the runtime decision for the execution of SPL variabilities, the effective test to verify the correct configuration of the system with their respective variabilities can be done just at load time and/or during the system execution.

• Exposure of full product line code. The code of all variabilities is always present in every SPL product, requiring only changes in parameters values for activating each of these variabilities. This may not be suitable for some business models, in which the product price depends on the amount and kind of variabilities enabled.

9. Known Uses

In recent years, the Conditional Execution design pattern has been used to implement different types of fine-grained variabilities in the information systems of the Informatics Superintendence (SINFO) at the Federal University of Rio Grande do Norte (UFRN) [SINFO / UFRN 2012 ] [GIS / SINFO 2012], such as:

• SIPAC – Sistema Integrado de Patrimônio, Gestão e Contratos: It provides fundamental operations for the management of the units responsible for finance, property and UFRN contracts, therefore, acting through activities “middle” of this institution. The SIPAC fully integrates administrative area since the request (material, service, supply of funds, daily tickets, lodging, informational material, maintenance of infrastructure) until internal distributed budget controls.

Among the several features of SIPAC using this pattern, we can cite:

o Lock Materials Purchase: It indicates whether the system will block the request of materials if the available balance is exceeded.

o Editing the Contract Occurrences: If the system possesses the operation to change/delete occurrences of contracts.

o Indication Request Period for Scholarships: The period in which the operation of request for financial aid for students is enabled.

• SIGRH – Sistema Integrado de Gestão e Recursos Humanos: It automates the human resources procedures, such as marking / changing vacation, retire calculations, functional assessment, sizing workforce, frequency control, trainings, online services and applications and functional registers, personal department reports, among others. Most operations have some level of

interaction with the nationwide system SIAPE (Sistema Integrado de Administração de Recursos Humanos), while others are only local services.

Among the several features of SIGRH using this pattern we can cite:

o The Training Server: It sets minimum grades and work hours that an employee must reaches to pass in a training course.

o Chief/Vice-Chief Lock Vacations: It sets whether the chief and the vice-chief of a unit can enjoy the vacations in the same period.

o Validation of the Employee Vacations: It defines if the validation rules at the moment of creating a vacation will be applied or not when the manager of the Personal Department creates the vacations for an employee.

• SIGAA – Sistema de Gestão de Atividades Acadêmicas: It automates the procedures in academic area through the modules: undergraduate, postgraduate (stricto sensu and lato sensu), elementary school, high school and technical school; submission and projects control and scholarship research, submission and extension actions control, submission and control of projects education (monitoring and innovations), library management system, reporting of academic professors productions, teaching activities and virtual distance learning environment called “Virtual Class”. It also provides specific portals for: rectory, teachers, students, tutors distance learning, coordination (stricto sensu, lato sensu and undergraduate), and evaluation committees (institutional and faculty).

Among the several features of SIGAA using this pattern we can cite:

o The Online Enroll: It sets whether students complete enrollment by the system or in person way only.

o Calculation of Academic Performance Indices: It calculates the indices that assess the academic performance of students in accordance with the strategies that are configured by the pattern.

o Method Evaluation of students: If students will be evaluated by grade, aptitude or concept.

o Punishment for the Delay in the Library: If users suffer fine or suspension for delaying loans of books in the library.

The mechanism of user authentication is another feature that uses the pattern, it is present in all three systems mentioned above, which can use a database or network authentication with LDAP.

Since one of the characteristics of the pattern is its simplicity of implementation, it can be applied easily in information systems. An example of these systems can be the

ERPs systems (software integrated enterprise resource planning). These softwares have features for presenting a large amount of variability because they are designed to be deployed in as many customers as possible and each of these customers have a business processes whose variability must be answered.

10. Implementation

This section presents an example of how the Conditional Execution pattern can be implemented. This example is the same shown in Section 2 about the punishment variability for the overdue materials (books, journals, proceedings, among others) from Library Management module. During the discussion of the example is highlighted how the forces involved with the pattern were implemented.

 Step 1: Identifying the Target Classes

Inside the SPL SIGAA, there are two variabilities related to the user punishment functionality: (a) cash fines for each day of delay in return of the material, and (b) suspend the user for a certain amount of days, during which the user cannot do new loans.

The using of the punishments functionality is related mainly with two scenarios of implementation in Library Management module: (i) the execution of a new loan when the system must not allow punished users get a new loans and (ii) at the moment of material return when the system must verify if it has been returned late and then it generates a punishment for the user. These two actions are performed in SPL SIGAA respectively by business classes LoanProcessor and ReturnLoanProcessor, which are characterized as Target Classes of the patterns. Both classes are part of the business layer of the SPL SIGAA which is organized following the tier architectural pattern [Buschmann et al 1996].

Inside the functionality user punishment, there is another action that involves print bill for pay library fines. This action should be only enabled if the variability “fine” is properly configured. Inside the SPL SIGAA, the places where this variability happens, which are characterized as Targets Classes are: (i) the Managed Bean PrintBillPayLibraryFinesMBean, and (ii) the following JSP pages: student_menu.jsp, professor_menu.jsp and server_menu.jsp.

Step 2: Mapping each identified variability to configurations parameters

After identification of Targets Classes, you need to create the parameters corresponding to punishment variability. For this case, there are two punishment variabilities. Thus, two parameters were defined:



The parameters are declared in a Java interface called LibraryParameters, which is shown in Listing 3. This interface is used by Targets Classes and Execution Manager to reference the parameters via Java source code. Each parameter has an identifier. These identifiers are created sequentially, so they are unique for the entire SPL.


Listing 3: Interface with parameters declarations.

After that, we need to persist parameters in the Parameters Repository. In the specific case of SPL SIGAA is used the technology of the database to persist parameters. It facilitates create, access and change parameter values. Thus, the creation of parameters is inserting them into the database. Listing 4 shows the creation of the SYSTEM_WORKS_WITH_FINE parameter in the database. Besides the identifier and the parameter value, other information such as a brief description and identification of the module of the SPL SIGAA that the parameter belongs are persisted, to facilitate its use through the system.

INSERT INTO comum.parameter (name, description, value, id_subsystem, id_system, identifier)


‘Define if the system will use fine like punishment’, ‘true’, 14000, 2, ‘2_14000_8’);

Listing 4: Parameters creation in repository

The extra information above referred is not essential to the operation of the pattern. It is not the purpose of the pattern to define of persistence techniques that have to be used, other techniques can be tried to implement the Parameters Repository.

The product derivation can be done by changing the parameter value in the database, as shown in Listing 5. An interesting strategy is creating an use case for system parameters management in order to pass the responsibility to choose which variability will be presented in a particular product for some system manager.

UPDATE comum.parameter set value = ‘false’ where identifier = ‘2_14000_8’;

Listing 5: Making product derivation using Conditional Execution pattern.

Thus, simply changing a value in the database determines the pattern characteristic of dynamic configuration.

Step 3: Implementing the Execution Manager

The Execution Manager is the main component in the implementation of this pattern. It contains a logical decision whether a particular variability will be performed or not.

Listing 6 shows a possible implementation of the Execution Manager. In this implementation a method checks if a given parameter variability happens retrieving the parameter from repository and returning its boolean value. If the parameter value is true, the variability is present in the product line and must be executed, if the value is false, the variability must be not executed.

Excution Manager simple

Listing 6: The Execution Manager

Normally, due to the use of this pattern, there is a considerable amount of access to the configuration parameters that can affect the system performance. The large number of data accesses to the Parameters Repository is because the system during its execution has to check in all places where variability may happen (variations points) if the variability is present in that particular product or not. Even if changes in a specific variability present in a product are rare, this checking is always necessary.

For this reason, it is recommended to adopt a strategy to minimize the number of accesses to the Parameters Repository. This strategy can be implemented in various ways. It is not the objective of the pattern to define a specific implementation strategy to achieve this aim.

How in this example of implementation we used a database system, to minimize the impact on system performance it was implemented a cache strategy. This implementation maintains information about the last time that the value of each parameter was synchronized with the value of the repository. When timeout is reached, the Execution Manager reloads the parameter value. This strategy is implemented by the method getParameter in Listing 6.

If you followed this strategy of cache, the Execution Manager should also keep an operation that forces a reload of a parameter or set of parameters whenever requested. This is useful when the value of a parameter is changed and this change should be immediately reflected in the behavior of the system.

The caching strategy used by Execution Manager ensures low impact on system performance, reducing queries to the repository, one of the forces that the proposed pattern undertakes to deliver.

This third step of the pattern implementation needs to be done once. This implementation can usually stay in the SPL architecture and it be used by all variability.

Step 4: Defining the Variability Implementation

The next step is to implement the specific code for each system variability. This code will be called by the Execution Manager if the variability happens in the product. Listing 7 shows a simplified code snippet of fine variability implementation in SIGAA SPL.

Fine Varability Implementation

Listing 7: Fine variability implementation.

Step 5: Calling Conditional Execution from Targets Classes

A conditional execution is implemented to generate the punishment for the material delay return depending on which of variability is currently enabled. Listing 8 shows the business class code ReturnLoanProcessor that is responsible to implement such functionality with the introduction of variability. To have a clear perception of this pattern, we can compare the code in Listing 8 with the code shown in Listing 1, which is presented in the same business class without using the Conditional Execution pattern.


Listing 8: Example of Conditional Execution in business layer

We can see in the code in Listing 8 that the implementation was carried out with a low impact, since no change was needed in the core of SPL. Besides, the call to Execution Manager is a simple implementation of the method invocation and it can be perfectly included at the point where the dynamic derivation should occur.

Another variability related to the delay of the loan is SIGAA SPL variability “Print Bill for Pay Library Fines”. This functionality should be performed only if the variability “fine” is active in the system. In this case, a link is shown to the user allowing the printing of payment bill. This is also a typical example of conditional execution of fine-grained variability that can be implemented using the pattern. Listing 9 shows a snippet of a webpage of LPS SIGAA, which includes a link to print the bill only if the variability “fine” is active. Moreover, it is also presented the code snippet of class PrintBillPayLibraryFinesMBean that is responsible for accessing the Execution Manager to verify the occurrence of variability in the product.

11. Variants

server_menu_with_variability 2


Listing 9: Example of Conditional Execution in view layer.

The Conditional Execution pattern can be used in a way that it performs more complex decisions than just boolean decisions that verify if a variability will be present or not in a product. This section describes two variant implementations of the pattern that are being using by SINFO/UFRN.

To illustrate the first approach, consider the functionality that checks the timeout between loans in the Library System modulo of SPL SIGAA. For this functionality there is an integer value that defines the minimum time, in hours, that a user can make a new loan of the same material. Besides, it makes possible to determine a minimum time between different loans for each product, this verification can be disabled in some products. Listing 10 shows the code of the Target Class where occurs this verification.

Loan Processor

Listing 10: Conditional Execution of Integer Variability

Instead of using a boolean parameter to determine if the variability should occur, it was created only one parameter of type integer. If this parameter value is greater than zero, the Execution Manager enables the execution of verification. At the same time, the parameter value is also used to calculate if the minimum time between loans was obeyed, throwing an exception if the business rule is not followed. Listing 11 shows an alternative implementation of the Execution Manager that verifies if a variation of type integer occurs, besides the method that returns this integer value to be used by the variability.

Excution Manager integer

Listing 11: Execution Manager for Integer Variabilities.

To this alternative implementation was added the information “type” to the parameter, beyond the information previously shown in Listing 4. This information allows determine how the variability should be treated. We call the variabilities that use an integer type parameter of “Integer Variabilities”. We emphasize that this was a solution adopted and it is not the goal of the pattern determines how these implementation details must be performed.

The second approach is based on removing of the dependency that the Targets Classes have with the Variability Implementation. In this approach, the Execution Manager doesn’ t just determine whether a V ariability Implementation will be

performance in a Target Class, but it instantiates and returns to the Target Class the Variability Implementation to be executed.

The solution adopted for this second approach makes use of the Strategy design pattern [Gamma et al 1995]. Some strategies are defined. The names of the classes that implement these strategies are mapping for parameters. If the variability is presented in the product, the Execution Manager instantiates the concrete strategies contained in those parameters.

For this approach was created a new type of parameter called “Strategy Parameter”. This kind of parameter doesn’t contain a boolean or integer value, but a class name that implements the strategy. The variabilities that use this kind of parameter we call of “Strategy Variabilities”. Figure 3 outlines the structure for this second approach. The functionality used is the same of Listings 1 and 8, the punishment of users for Library Management module of SPL SIGAA.

Class Diagram Strategy Conditional Execution

Figure 3: Example of Strategy Variability implementation using Conditional Execution pattern.

In this approach the method getVariabilityStrategies of Execution Manager receives a map of parameters. The map keys are boolean parameters which determine whether the variabilities happen and the map values are strategy parameters containing concrete strategies to be instantiated. Listing 12 contains the code for a possible implementation of the method getVariabilityStrategies.

Excution Manager strategy

Listing 12: Example of Execution Manager for Strategy Variability

If the variability contained in the map key occur, the Execution Manager instantiates the strategy contained in the map value, returning to the Target Class a list of strategies that should be executed in the product and performing the product derivation at runtime.

Listing 13 shows the implementation of the same variability shown in Listing 8, but now using the approach of strategy variability modularizing to treat the functionalities “fine” and “suspension”.


Listing 13: Target Class using Conditional Execution for a Strategy Variability.

In this context, to add a new variability to SPL is necessary to create a new strategy punishment that “extends” the class UserPenaltyStrategy. It must insert the new parameters to the variability in Parameters Repository and add them to the map passed as a parameter to the method getVariabilityStrategies of the Execution Manager. Thus, a new strategy is instantiated by the Execution Manager and returned to be performed without the need to add a new conditional statement in the Target Class always that a new variation is added to the product line.

Listing 14 shows an example of information about three kinds of parameters that can be used to implement this pattern.

-- boolean parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type )

VALUES (‘2_14000_8’, ‘ SYSTEM_WORKS_WITH_FINE’, ‘true’, 2, 14000, 1);

-- integer parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type)

VALUES (‘2_14000_10’, ‘MINIMUM_TIME_BETWEEN_LOANS’, ’24’, 2, 14000, 2);

-- strategy parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type)


‘br.ufrn.sigaa.circulacao.negocio.SuspensionDefaultStrategy’, 2, 14000, 3);

Listing 14: Example of three kinds of parameters used by the suggested implementation of the pattern.

Other variants to the pattern implementation can be created, it depends if will appear other variabilities which behave differently from those ones described in this paper.


We are grateful to Professor Dr. Eduardo Guerra for his valuable suggestions during the shepherding process that contributed to a broader understanding of the proposed pattern. We also thank all the suggestions given by the participants of the Writers’ Workshop of SugarLoafPLop’2012.


Buschmann, F., Meunier, R., Rohnert, H., Sommerlad, P., Stal, M. (1996): Pattern- Oriented Software Architecture, A System of Patterns, vol. 1. Wiley.

Clements, P., Northrop, L. (2001): “Software Product Lines: Practices and Patterns”, Addison-Wesley Professional, 2001.

Czarnecki, K., Eisenecker, U. (2000): “Generative Programming: Methods, Tools, and Applications”, Addison-Wesley, 2000.

Gamma, E., Helm, Richard., Johnson, R., Vlissides, J. (1995). “Design Patterns: Elements of Reusable Object-Oriented Software”, Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.

Kästner, C., Apel, S., Kuhlemann, M. (2008). “Granularity in software product lines”. In Proceedings of the 30th international conference on Software engineering (ICSE ’08). ACM, New York, NY, USA, 311-320.

Kästner, C., Apel, S. Virtual Separation of Concerns – A Second Chance for Preprocessors. Journal of Object Technology. Vol. 8. No 6. 2009

SIG/SINFO – Management Integrated Institutional System of Informatic Superintendence at UFRN: Available at: http://www.info.ufrn.br/wikisistemas, Oct 2012.

SINFO/UFRN – Informatics Superintendence at UFRN (2012). A vailable at: http://www.info.ufrn.br, Oct 2012.

Weiss, D., Lai, C.. (1999): “Software Product-Line Engineering: A Family-Based Software Development Process”, Addison-Wesley Professional, 1999.

janeiro 27, 2012

Acessando Banco do Brasil a partir do Chrome no Linux

Filed under: Uncategorized — jadsonjs @ 3:54 pm

Essa aqui é para quem está com dificuldades de acessar o site do Banco do Brasil a partir do Linux utilizando o navegador Chrome.

  1. Primeiramente será preciso instalar a Máquina Virtual do Java na sua máquina, como já demostrado neste post: https://jadsonjs.wordpress.com/2009/02/02/instalando-java-no-ubuntu-linux/
  2. Depois será preciso copia o arquivo libnpjp2.so do diretório lib dentro do diretório de instalação da JRE, para o diretório plugins do Chrome.

O comando abaixo realiza essa tarefa, devendo apenas trocar os caminhos mostrados para os locais de instalação do java e chrome no seu computador :

sudo ln -s /usr/local/java/jdk1.6.0_23/jre/lib/i386/libnpjp2.so /opt/google/chrome/plugins

cria um link simbólico (atalho) do arquivo libnpjp2.so para o diretório plugins do chrome.


Reinicie o Chrome e digite o texto seguinte na barra de endereço do navegador:  chrome://plugins

Pronto !  O plugin Java(TM) Plug-in 1.X,X_XX deve ser mostrado. E será possível acessar o site do Banco de Brasil por ele.

abril 2, 2011

Desabilitando rede EDGE Samsung Galaxy 5 com android 2.2

Filed under: Configuração/Instalação — jadsonjs @ 7:01 pm

Atualizei o meu Samsung Galxy 5 para o android 2.2 – atualização ofical disponibilizada pela samsug no final de março de 2011.

A atualização “resetou” as minhas configurações de redes sem fio.Resultado, a rede de dados EDGE foi ativada novamente, e como eu não tenho plano de dados, isso me custou muitos R$ dos meus créditos antes que eu descobrisse como desativá-la.

O caminho normal é Menu -> Configurações -> Conexões sem fio e rede > Redes Moveis > Desativar conexão de dados. Mas essa opção apareceu desabilitada para mim assim que a atualização do Android foi concluída :( .

Assim procurando na internet achei um atalho que me salvou da falência:

Segurar o botão de desligar até aparecer um menu na tela. A primeira opção é “Redes Móveis”.  Onde pode-se ativa-la desativa-la.

Obs.: Só desliga a rede de dados móvel (2G/3G), não a rede WiFi.

A desativação também ajuda a poupar bateria. :)

Apanhado de siglas utilizados nessa área de comunicações móveis:

GPS -> Global Position System. Sistema de posicionamento global  via satélite.

GSM -> Global System for Mobile Communications. Rede de comunicação móvel digital. É visto como um sistema de telefone celular de segunda geração, o famoso 2G.

GPRS -> Troca de dados por pacote para sistemas GSM. Também chamado de 2.5G.

EDGE -> Rede de dados para GSM. Aumenta a velocidade das redes GPRS.

UMTS -> A nova tecnologia para comunicação móvel, são as badaladas redes 3G.

HSDPA -> Aumenta a velocidade das redes UMTS. Chamado comercialmente de 3.5G ou 3G+.

março 7, 2011

Enums em Java: utilização e persistência

Filed under: Código e Algoritmos — jadsonjs @ 6:52 pm

Este artigo mostra as vantagens na utilização de constantes enumeradas em Java em vez de simples constantes inteiras.  Descreve também como fazer um mapeamento simples para persistir e recuperar o valor inteiro da constante enumerada no banco.

Palavras Chaves:  Enums, Java, Hibernate, @Enumerated, ORDINAL

Enums em Java: utilização e persistência


fevereiro 2, 2009

Ubuntu: Como configurar um teclado padrão americano p/ aceitar acentos pt_BR

Filed under: Configuração/Instalação — jadsonjs @ 8:08 pm

Para voce que tem um computador com teclado americano como eu mas gostaria de usar acentos e “ç”.

Muito fácil no Ubuntu 8.10:

Sistema -> Preferencias -> Teclado.

Na aba “Disposições”, clique em um botão com um “+” para adicionar uma nova disposição.

Abrirá um nova Janela,

* Onde tem paíz coloque: “Estados Unidos”

* E onde tem variante coloque: “EUA Internacional (com teclas acentuavéis)”

Pronto, remova a desposição que existia, selecione a que foi criada como “padrão”. E clique em “Aplicar (Todo o sistema)”

OBS.: Para digitar o “ç” digite o acento agundo + “c” . (é como se você quisesse acentuar o “c”)

Para digitar qualquer acento sozinho. Precione a tecla do acento + “barra de espaço”

Older Posts »

O tema Silver is the New Black. Crie um website ou blog gratuito no WordPress.com.


Obtenha todo post novo entregue na sua caixa de entrada.