Tuesday, November 29, 2011

WARN AjaxContext:358 - Current Skin is not found


org.ajax4jsf.framework.skin.SkinNotFoundException


Comment the ajax's SKIN configuration on web.xml file, or set it to DEFAULT.





Sunday, November 20, 2011

Instalando o Windows Ultimate no Vaio



Motivação
Liberar recursos - disponibilizar mais memória e CPU para as aplicações de trabalho.

Objetivo
Desempenho (rapidez), confiabilidade e maior número de aplicativos de ambiente de trabalho disponíveis concomitantemente.

Estratégia
Trocar o ambiente original do fabricante, por outro específico e otimizado para as necessidades profissionais, utilizando uma versão de Windows com melhor administração de recursos - Ultimate.

Procedimento resumido
Utilizar os drivers originalmente já instalados no sistema original.
Método: criar um DVD com a cópia do diretório "C:\ProgramData" e utilizá-lo para atualizar os drivers que apresentarem problema de instalação.

Resultado Obtido
No final do texto há uma comparação entre a situação inicial e a final, no item "Resultados Observados ao Longo do Uso".


Acima, você tem um resumo rápido da situação.

Se desejar detalhamento, poderá encontrar abaixo no item
"Instalando o Ultimate a Partir dos Drivers Pré-Instalados Originalmente"
(em verde claro).



O preâmbulo a seguir visa passar um contexto de mercado que poderia ser mudado.


Afinal, nós consumidores quando formamos opinião, mudamos muita coisa!




Máquinas Vaio vêm geralmente com Windows Home Premium instalado e customizado (Vaio Care).
Seria muito mais prático apenas utilizar o sistema já instalado de fábrica, com tudo acertadinho, pronto apenas para usar.

Então por que não usar o sistema original?

Eu venho usando notebooks Vaio há mais de três anos, exclusivamente para fins profissionais na área de TI.
E tenho sempre os mesmos problemas: pesada, lenta e consumindo muita memória e CPU em coisas que não me são úteis.

O hardware é muito bom, e se não o fosse, os dois anos de garantia dados às máquinas compradas no Brasil, comprometeriam a lucratividade do fabricante.

É por essa razão que compro Vaio.
Garantia de 2 anos e um hardware de qualidade confiável.

E tem dado certo, porém o sistema operacional que a empresa configura busca atender às necessidades populares de consumo.

Compreensível, porém esse tipo de configuração não é adequada para usuários que "trabalham pesado", exigindo intensamente os recursos da máquina com seus aplicativos.
Esse tipo de profissional necessita de cada mega de memória e cada clock de CPU disponíveis para dar conta de ambientes mais sofisticados, tais como outros sistemas operacionais rodando em máquinas virtuais, redes virtuais e aplicativos de desenvolvimentos pesados que consomem vorazmente recursos da máquina,  concomitante a muitos outros aplicativos auxiliares de trabalho que precisam estar lá, abertos à sua disposição, a exemplo de geradores de diagramas UML, interfaces com SGDB, frameworks, etc.

Veja ao final do texto, porque valeu a pena tanto esforço para trocar do sistema "Windows Home Premium - Vaio Care" original para o Windows Ultimate.

A primeira tentativa, após fazer um backup do sistema operacional original, foi frustrante.
Busquei o suporte Vaio por email, que remeteu para o atendimento telefônico.
Embora o profissional de suporte tenha se empenhado em oferecer o procedimento alternativo, fez questão de lembrar que a Vaio não dá suporte oficial para um  upgrade de sistema.

É isso mesmo!
A Vaio não oferece garantia de suporte a quem precisa de um upgrade do próprio Windows que vem instalado na máquina!!!
Ao invés disso, o que oferecem é algum procedimento complementar para "tentar" ajudá-lo a resolver alguns problemas.




Instalando o Ultimate a Partir dos Drivers Pré-Instalados Originalmente

Ao instalar um novo sistema operacional, o primeiro grande desafio é o "reconhecimento de drivers".

O Windows 7 Ultimate, quando instalado no notebook Vaio VPCF135FB (i5/6GB RAM), não reconheceu controlador de rede, barramento pci2, PM55 Express Chipset LPC Interface Controller e Barramento PCI 3."

Enviei email ao suporte Vaio, e obtendo resposta busquei seguir o procedimento indicado por eles (em anexo, abaixo), mas o sistema tornava-se instável logo ficando sem condições operacionais e obrigando uma nova instalação.

Isso ocorria após a tentativa de instalação de drivers da placa-mãe, seguindo a orientação recebida, cujo fragmento segue abaixo:

"baixar todos os drivers referentes à placa mãe (motherboard):
Original - Intel® 5 Series 6 Port SATA AHCI Controller Driver
Original - Intel®Turbo Boost Technology Driver
Original - Intel® Chipset Driver"


O suporte telefônico sugeriu um procedimento alternativo, que também anexei ao final, pois pode ser útil a alguém.

Diante da situação, estava sem solução, pois os procedimentos sugeridos foram ineficazes.

Observando os modelos Vaio que oferecem opção para Home e Ultimate, a política do fabricante e etc. cheguei à conclusão que certamente eles evitariam aumentar os custos criando coisas diferentes desnecessariamente.

Verificando a documentação da Microsoft sobre os dois sistemas (Premium e Ultimate), achei que valia considerar a compatibilidade de drivers entre eles.

O problema não estaria "no que fazer", mas "em como fazer", ou seja, os drivers poderiam ser os mesmos, mas dependeriam de como fossem instalados.

Com base nisso, criei um DVD com a cópia integral e original do conteúdo do diretório "C:\ProgramData" da instalação original do Windows Home Premium.

Não precisaria tudo isso, mas DVD é barato e tempo é caro. "Ficar caçando drivers toma tempo"...

Ao instalar o Ultimate, verifique se a sua cópia é para upgrade ou instalação full (completa).


Se for para upgrade, instale o Ultimate sem formatar a partição (ou disco, se for o caso).
Se for não for para upgrade, FORMATE a partição e então instale o Ultimate.
Por que?
Se não atentar para esses detalhes, você terá problema com a validação do Windows!
Só por isso, porque o procedimento descrito aqui foi testado nos dois casos, e obteve sucesso em ambos, reconhecendo todos os drivers.


Após a instalação do Ultimate, vá para o gerenciador de dispositivos e verifique quais os dispositivos (devices) estão exigindo cuidados - todos aqueles com "warn", um ícone amarelo.
Aqui vai uma dica importante: comece pela ordem de importância de um driver para o sistema.
Ou seja: placa-mãe e depois periféricos.
Deixe o USB e o supérfluo por último, quando o principal já estiver funcionando.

Clique no driver com problema e selecione a opção "atualizar driver".
Se desejar, pode acessar de outras maneira, o que importa é chegar à janela onde você vai digitar o caminho onde se encontra o driver para o dispositivo (device).
Basta apontar para o DVD que você gerou no passo anterior.
Demora um pouquinho, mas se retornar mensagem de sucesso, tudo bem! Resolvido.
Se não obtiver sucesso, continue repetindo para todos os outros restantes, sem se importar com o insucesso anterior.
Muitas vezes, a solução de um driver viabiliza a solução de outro.

Reinicie a máquina.

Repita o procedimento mais uma vez, se ainda houver algum dispositivo ainda com problema.


Se persistir, tudo bem, há solução.
Você utilizará para esses casos o executável respectivo ao driver, cujo download dever ser feito do site da Vaio, de acordo com o seu modelo:
http:/esupport.sony.com/BR
ou
http:/esupport.sony.com/US

Execute o aplicativo normalmente, e vá seguindo a orientação do instalador.

No meu caso foi suficiente e todos os drivers instalaram com sucesso, sendo que apenas o driver de USB exigiu executar o aplicativo específico.

Se no seu caso você tiver problemas ao executar a aplicação de instalação de driver da Vaio, leia o segundo procedimento, aqui anexado ao final - "Procedimento de Instalação Sugerido Pelo Suporte Telefônico".
Ali, descreve como alterar as propriedades do aplicativo para torná-lo a executar.
Utilizei esse procedimento em uma das tentativas anteriores com sucesso em alguns drivers, mas não em todos.

Neste procedimento que aqui descrevo, não foi necessário.


Boa sorte!
Porque sempre precisamos... : )


NOTA:

Os procedimentos sugeridos pela Vaio foram aqui transcritos com a intenção de facilitar soluções a quem precise.

Aproveito a oportunidade para agradecer o empenho do suporte da Vaio na tentativa da solução do problema.



Procedimento de Instalação Sugerido Pelo Suporte via email

Caso o modelo de seu VAIO seja o VPCF135FB, favor acessar o link:

http://esupport.sony.com/BR/perl/swu-list.pl?Change_Template=1&session_id=464d4ef4f72e819a497c7bd87c090ab2&mdl=VPCF135FB

e baixar todos os drivers referentes à placa mãe (motherboard):

Original - Intel® 5 Series 6 Port SATA AHCI Controller Driver
Original - Intel®Turbo Boost Technology Driver
Original - Intel® Chipset Driver

Para o controlador de rede, é necessário fazer o download do driver Original - Marvell® Yukon® 88E8057 PCI-E Gigabit Ethernet Controller Driver, encontrado na opção Network.

Para que os drivers funcionem corretamente, é necessário realizar o seguinte procedimento:

1 - Ao fazer o download do arquivo salve-o na sua área de trabalho para um fácil acesso. Após o download ter sido concluído peço, que faça uma instalação normalmente, começando com um clique duplo sobre o arquivo.
2 - Uma mensagem aparece no final da instalação dizendo que o programa pode não ter sido instalado corretamente.
3 - Quando isso acontecer, sempre escolha a opção: reinstalar usando as configurações recomendadas, e faça uma nova instalação.
4 - Ao final pode dizer ou não que o driver apenas roda em Windows Vista, aparecendo ou não clique no arquivo do driver com o botão direito do mouse e vá em Propriedades.
5 - Selecione a aba Compatibilidade e vá no botão Alterar as Configurações de Todos Usuários e na nova janela que abrir desmarcar a opção do modo de compatibilidade, independente da opção selecionada abaixo (ficará assim com tudo desmarcado).
6 - Clique em Aplicar, Ok e Ok de novo e reinstale o driver. Feito isso após a instalação não haverá nenhuma mensagem de erro, basta reiniciar o notebook e o driver estará instalado.

Após, habilite a exibição de arquivos, pastas e unidades ocultas. Em qualquer janela do Windows Explorer em primeiro plano, aperte a tecla ALT, clique em FERRAMENTAS > OPÇÕES DE PASTA, clique na aba MODOS DE EXIBIÇÃO e marque a opção MOSTRAR ARQUIVOS, PASTAS E UNIDADES OCULTAS;
2 - Instale os drivers dos dispositivos pendentes (como descrito acima).
3 - Abra o gerenciador de dispositivos: "Iniciar > Computador (clique com o botão direito)> Gerenciar";
4 - Clique com o botão direito sobre o driver com um ponto de Exclamação amarelo e vá em "Atualizar Driver";
5 - Selecione a opção "Procurar Software De Driver No Computador" ;
6 - Faça a busca do driver dentro da pasta "C:\USERS\**nome da conta do usuário**\APPDATA\LOCAL\TEMP";
7 - Clique em "Avançar" e, após a instalação do driver, clique em concluir e reinicie o computador se for solicitado.

Lembrando que o notebook VPCF135FB foi projetado para operar com o Microsoft® Windows® 7 Home Premium 64-bit e alguns drivers podem não ser reconhecidos e ou não funcionar corretamente, pelo fato de o sistema operacional não ser o original instalado no VAIO.

Caso tenha outras dúvidas ou problemas de suporte técnico, por favor entre em contato conosco. Será um prazer ajudar.
Obrigado por escolher a Sony.

Para quaisquer futuras solicitações de suporte técnico, por favor, não deixe de visitar:

http://esupport.sony.com/BR

Atenciosamente,


Procedimento de Instalação Sugerido Pelo Suporte Telefônico

1. Habilitar a visualização dos arquivos ocutos em painel de controle, opções das pastas.
2. Antes de executar o driver, abrir suas propriedades, tab compatibilidade, em Modo de Compatibilidade assinalar
Executar este programa...
escolhendo a opção Windows XP Service Pack 2.
Em "Nível de Previlégio" assinalar "executar como administrador".
3. Depois de instalar os drivers - são 3, consulte a lista de drivers ou observe os títulos à medida que os intala,
vá para o painel de controle, gerenciador de dispositivos, selecione o primeiro nó (root), que tem o nome da máquina,
e no menu ação, escolha "Verificar se há alteração de hardware".
Nota: o suporte assinalou como principais os seguintes drivers:
MRDWLL002253080042
SOAOTH-00228371-0042.EXE4. Se o dispositivo ainda apresentar incompatibilidade, informando que o driver não foi instalado com êxito,
então, click sobre o device com problema, e selecione a opção de contexto (botão direito do mouse) "Atualizar driver"..
Vai apresentar duas opções, escolha aquela que permita indicar o caminho o devemos encontrar o driver adequado.
O driver ao ser executado na etapa anterior, gravou em um pasta os arquivos necessários.
Esta pasta fica no diretório do usuário (C:\Users ou C:\Usuário) no diretório appData\local\temp.
É este caminho que deve ser indicado.
5. Não obtendo sucesso, pode-se procurar por drivers adicionais específicos para o Windows Ultimate de outros notebooks equivalentes.
Um dica passada pelo suporte é procurar por:
VPCCS360A (not found at 08/15/11 12:58:18)
E escolher a opção do Ultimate.
O suporte está utilizando os drivers desta máquina para solucionar este tipo de problema.
6. O suporte deixa claro que a Sony não oferece solução para viabilizar todas as funcionalidades originais quando uma instalação diferente
daquela oferecida pela fábrica é instalada no notebook. Segundo o suporte, consegue-se a maioria delas, mas depende da máquina, pois
algumas vezes o mesmo procedimento funciona ou não.
7. Para DRIVES DE FUNCAO, buscar por 's'


Por que vale a pena tanto esforço para trocar do sistema "Windows-Vaio" original para o Windows Ultimate.

Bem, se você é um usuário que "pega pesado", acho que vale a pena.
Não importa se você usa sua máquina para jogos ou programar.
Em qualquer caso, sempre desejamos desempenho!
Eliminando o desnecessário, haverá mais desempenho e mais recurso disponível.
Aqui vão alguns fatos.

NOTA:


Eu penso que seria uma boa sugestão para a Vaio, ou outro fabricante, que os recursos pudessem ser ativados ou desativados através de uma interface visual simples.
Isso amenizaria o problema onde a diferença de fins exige que cada uma possa escolher o que é melhor para si mesmo, sem ter que compartilhar coisas desnecessárias, ou gastar um bom tempo para obter isso por meios próprios.





Resultados Observados ao Longo do Uso


Memória disponível total = 6GB
CPU = Intel i5

Instalação original do Windows 7 Home Premium - Vaio Care

Uso da memória ao iniciar o sistema (%) = 33 a 51
uso da memória ao utilizar os aplicativos de trabalho, incluindo máquina virtual (%) = 35-98 (Nota: a máquina "congelava" ao atingir valor superior a 98% do uso da memória)

Constantes travamentos em virtude de processos aguardando disponibilidade de CPU (ou seja, máquina mais lenta) ou em virtude de "swap" de memória, paginação e limpeza(memória modificada para "em espera").

Conclusão:
Inadequada para o uso a que se destinava.


Instalação original do Windows 7 Home Premium da Vaio após limpeza

Eliminei muitos aplicativos da instalação original da Vaio com o propósito de liberar recursos e bloqueie outros tantos (msconfig, e etc.)
Mantive tudo o mais sem alterar.

Uso da memória ao iniciar o sistema (%) = 19 a 36

Uso da memória ao utilizar os aplicativos de trabalho, incluindo máquina virtual (%) = 21-90 (Nota: valores superiores a 85% promovem constantes swaps de memória, travando a máquina)

Travamentos regulares devido a "swap" de memória, paginação e limpeza(memória modificada para "em espera"), principalmente se o uso de memória ficar superior a 70%, em virtude de "swap" de memória e limpeza (o led de HD fica acesso e a máquina super lenta)

Conclusão:
Melhorou bastante, mas ainda causava lentidão nos trabalhos diantes de constantes travamentos regulares.
A troca de ambientes, entre máquina virtual e hospedeira causa swaps intensos após longos períodos em que se utiliza apenas uma delas.


Instação do Windows 7 Ultimate original com todos os updates até SP1

Uso da memória ao iniciar o sistema (%) = 15 a 21

Uso da memória ao iniciar os aplicativos de trabalho, incluindo máquina virtual (%) = 49-61

Travamentos ocasionais em virtude de "swap" de memória, paginação e limpeza(memória modificada para "em espera").



Conclusão:


O Windows 7 Ultimate, instalado apenas com o básico, apresentou-se um ambiente de trabalho melhor que os ambiente anteriores, embora ainda longe do desejado, demandando quantidade consideravelmente menor de recursos, permitindo utilizar máquina virtual com todas as ferramentas de trabalho em execução concomitantemente, resultando em uso médio de memória inferior a 2/3 da capacidade total.

A troca de ambientes entre máquina virtual e hospedeira, após algum tempo de uso de apenas uma delas, causa um ou dois swaps intensos inicialmente, e depois estabiliza, sem ocorrências posteriores relevantes.

Ambos ambientes, tanto o da máquina hospedeira, como aqueles nas máquinas virtuais (Linux/Windows/Solaris), trabalham concomitantemente, permitindo alternar entre eles, com alguns swaps de memória.


Essas características de um ambiente suportando máquina virtual são comuns a qualquer dos ambientes testados, porém ficam agravadas proporcionalmente à utilização dos recursos disponíveis, ou seja, os períodos de indisponibilidade diminuem com maior disponibilidade de memória e CPU, como esperado, portanto torna-se fundamental preservá-los para o que mais importa.





Installing Windows 7 Ultimate on Vaio




or...
UPGRADING VAIO's WINDOWS HOME PREMIUM TO WINDOWS ULTIMATE

This procedure is a summary of the original text in portuguese, which contains the context and details.

When installing a new operating system, one of the challenges is the drivers' setup.
Here, I tell you a fast and easy alternative from my direct experience.

Suppose that you desire to upgrade the original Windows, usually Home Premium, to Ultimate, or yet install the Ultimate from scratch.
Anyway, you may get this situation: opening the device manager you get many warnings telling you that some drivers are not working properly.
How to fix this?

Burn a DVD with the whole content of C:\ProgramData directory from you original installation.
The one that comes with your notebook.
Certainly you've done an image, or backup. Restore it on another partition and burn the DVD.

Note:
if your Ultimate is an upgrade license, install the Ultimate without formatting the original partition, otherwise, if full, format it.
Why?
It happens that if you ignore this detail, you may have problem with your windows activation.

Sometimes you can have the right drive.
The point is not about what you have, but how you handle it.

Once the installation is complete, go to the device manager and check the devices with warnings (yellow icon), indicating that they are not properly installed.
Right click over it, and choose "update driver" option.
Certainly, you can get this by many ways, but what matters is to get the panel where you can point the directory from which the driver is supposed to be found.
Point to the DVD that you burnt, on the root, or top (ProgramData folder).
Just click to go.
Check the return.
If successful, go to the next.
If not, don't worry, go to the next anyway.

IMPORTANT TIP:
Begin with the most important drivers - first motherboard's.

After you've finished, restart the system.
Check again the device drivers.
Repeat the procedure one more time over the remaining ones, that still have warnings.
If still unsuccessful, download from Vaio site the respective executables to install the defective drivers.

The point is that sometimes one driver installation may depend on another.
If you were successful with the main drivers (motherboard's), you'll have a good probability to fulfill you task with the remaining ones, using the executables.

I tried using just the downloaded executables, strictly, but It didn't work.
In my case, motherboard did not install from the executables.
And without motherboard working, the system got instable, and the others failed too.

The procedure shown here, using the stuff from the original installation was successful for all defective drivers, except the USB, which I used its executable.

If you get problem running the executable, try to change its properties.
Got to the compatibility tab, switch to execute as administrator, and check to use "compatibility mode". Try first Windows XP(service pack 2),
according to the Vaio's direction about a notebook with Intel i5.


This procedure, using the original stuff, was very successful for me, when the "usual one" failed.

Good luck.



Sunday, October 30, 2011

JUnit exception: java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

Problem

Although having the junit.jar on a JEE project, when running the junit test class, the following exception is generated:

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

Solution


Goto http://www.jarfinder.com/ 


On the class search tab, search for the missing class shown on the stack trace output, typing:


org.hamcrest



On the output list it's shown newer versions.
Choose one, for instance junit-4.4.jar and download it using the  jar search tab beside the class search tab.

Switch the older version of the jar file on the project by the newer one.
To check, refresh your project, rebuild if necessary.
On the junit class file, type part of the import statement to activate the autocomplete. For instance:

import org.hamc

At this point, if using netbeans or eclipse, the autocomplete will show the options.
If the options shown are respective to the missing class, the problem is solved and you're ready to run the junit class.

The same procedure can be used for such other problems.



Thursday, September 22, 2011

Software Tips - Sharing with you what It works for me! :)


Today we need zillions of tools to handle our tasks on the digital world.
Without them, we're really out, dead or get mad.

If you just like those kind of original stuff that comes with your operational system, these tips are not for you, but if you're the kind like me that is always searching a way to improve your system handling, here you're gonna find some shared direct experience that it was pretty useful and successful for me on Windows and Linux.

Sorry, but I am out of Mac just because I have no time to add a new environment to my private network for now, but who knows!...  Anyway, If you are a Mac fan, you're welcome too. Just ask me to add a link here to your blog or web page with the same subject of this one, of course.  : )

This a dynamic page, which can be updated at any time, when new information comes out.

For today, I'm gonna comment about the most used ones for myself, because other way, I'd have to spend all the week here.  
I really love software, and it couldn't be different - I'm a system analyst. 

Don't think that every software commented here is error free.
Just God is error free.
Nevertheless, their bugs don't avoid having an excellent performance on general handling.

Here we go!


File Exploring 
If you use Windows Explorer then  try xplorer2 .
At first sight, it's like getting into a jet dashboard.
Much more powerful. Just a question of getting accustomed to it.
You'll navigate much faster on your directories.
There is a prior free version for 32-bit systems named 2xplorer.
It's simpler but still pretty good.



File Download
Super important. We download something all time, but if you have a list of things to download, try JDownloader.
It's free and works pretty well.
There are many features.
You can select a raw text containing links, press Ctrl+U to add the text and the application filters the existent links. It also has excellent support for plugins. If you are registered on file hosting sites, like rapidshare, hotfiles, etc., your premium account can be added, and so on.



Stream and Web Stuff Download
Try JCopia.
Capture flash video and audio from any website to your computer
Have you ever thought how to download video and audio from flash players on internet sites like Youtube, Google Video, MySpace, DailyMotion, Metacafe, Break, Blog sites of your friends with embedded audio and video content and so on?
That's it. It captures, saves and play online media.
It's possible to get a free copy. Email jjohnson@jiteco.com or contact at facebook.




Image

PhotoFiltre
A simple software to use with "print screen".
Fast, light and practical.
I love it when creating documentation on HTML.

A more sophisticated one?
Go to gimp .
This software is so "classic" that I feel uncomfortable to comment.
Not necessary.  : )

Of course there other good ones.
You can add your comment here. Welcome.

Have fun.




Friday, September 16, 2011

Máquina Lenta

Hoje, diante de uma máquina lenta, onde tudo que parecia poder ter sido feito já fora, resolvi olhar o espaço disponível em disco da partição C.
Estava no limite.
Redimensionei a partição C: aumentando-a em 20GB, utilizando o aplicativo EASYUS partition tool
(http:/www.easeus.com/partition-recovery/), versão HOME (gratuita ).

Sucesso.

A ferramenta deixou ótima impressão, tanto na apresentação de interface quando no desempenho.
Para realizar a tarefa, antes era necessário deletar outra partição para liberar espaço para uma partição de dados "D:", que então
seria movida (250GB), ocupando o espaço liberado, e finalmente deixar espaço livre para o redimensionamento de C:.

Muitos dados, embora com backup, a questão é tempo.

O resultado final foi que a máquina retornou à agilidade que deveria ter.
O problema era que, sem espaço em disco, o SO fica com pouco espaço para manejar os arquivos temporários e memória cache.

Como a máquina era um nó de rede também servidor de dados, todas as outras que a utilizavam, por conseguinte, também ficaram mais
rápidas, já que os mapeamentos locais de rede dependem da velocidade da máquina mapeada.

Tudo resolvido em poucos minutos.

Gostei do EASYUS.

Máquina lenta? Já gastou sua munição de soluções?
Tente ampliar o espaço disponível na partição C:.


Sunday, August 28, 2011

Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath



If you get the following message on a Hibernate project:

204 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the           classpath. Hibernate Search is not enabled.                                                                 
that' because in some way  it was not possible to find the respective library that contains that class.
Check these two possibilities:

1. If using Eclipse, first refresh your project then go to the menu, preferences, build path, library tab.
Press the "add jar" button and point to your project's lib directory.
If it happens to appear any jar file that's because it was not registered on the classpath. Select all of them and press "ok button".
Return to your project and run again. Sometimes it's advisable to "clean" the project before just to make sure.

2. If the problem is not solved by the prior procedure, certainly the respective library is missing on your project's environment.
To solve this, first download the Hibernate's libraries at http://www.hibernate.org/downloads
For instance, the "hibernate-search-3.4.1.Final.tar.gz" or the zip version or choose a newer version if your project uses newer libraries or older version if the other way around.
Now, the fastest way is to copy the following files to your project's lib:

hibernate-search-3.4.1.Final.jar
hibernate-search-analyzers-3.4.1.Final.jar
hibernate-search-infinispan-3.4.1.Final.jar

Remember that you need to refresh you project and add the respective jars on the project's build path - see description on first procedure, above, and repeat it.

If after that you still get other error or warning messages that is about "missing things", do the following to solve this problem at once:

Select all the jars from the downloaded version of hibernate and copy them to a temporary folder.
Begin comparing the versions of all your project's jars with the temporary folder that contains the hibernate's jars.
Remember that the versions shall be compatible, so it's reasonable that the versions should be most close as possible, better if they match, when possible.
Replace your project's jar with the newest versions considering you project's version and complement with the other files that are missing. This procedure will help you to avoid having new problems in the future.
After all missing files were added to your project, refresh it and update the build path as commented above.
Remember that this procedure is valid for a Hibernate project.

You project will shall run without error/warning messages now.

NOTE:
If you use hibernate Annotations, you do not need to configure the event listeners, they are registered for you transparently.


Wednesday, August 24, 2011

Convert a PostgreSQL Database from LATIN1 to UTF8



At first I tried a procedure using iconv.
This procedure is described below and it was based on one found at http:/bryan-murdock.blogspot.com/2008/11/convert-postgresql-database-from-latin1.html
but unfortunately it didn't work for me.
So, I decided to try another alternative, that should be simple and fast, which is described here.

Procedure using editor's encoding and manual settings

Dump the database:
pg_dump -U postgres rental > rental/rental.dbs.out


Edit the file dumped on the prior step using an editor which has encoding features.
My default editor is SciTE and it was the editor that I used to do this.
Note: this editor has Windows and Linux versions.
On the editor, change the original encoding used for the file, switching to UTF-8, and "save as" the document with a new name.
Here, on this procedure I've saved it as "rental/rental.dbs.out.utf8".

After that, change the PostgreSQL's encoding on the same file.
You'll find something like this:
--
-- PostgreSQL database dump
--

SET client_encoding = 'LATIN1';
SET standard_conforming_strings = off;
...


Switch to:
--
-- PostgreSQL database dump
--

SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
...


Save the document and exit.
Remember, save it as UTF-8.

NOTE: if the dump file opens on the editor and shows gibberish and goofy signals instead of the normal data,
you must check your editor encoding or the procedure used to generate the dump file.
The text must appear legible as it should be.

Drop the old latin1 database:
dropdb rental

Log as postgres or another user with the necessary privileges:
psql -U posgres

Create the new utf-8 database:
create database rental with template = template0 owner = postgres encoding = 'utf8';

Connect to the new database created:
\c rental

Restore the converted dumped file - the one which you edited and saved as UTF-8 changing its encoding:
\i rental/rental.dbs.out.utf8

It's done.

Below, you find the final checking topic with the result obtained.


Handling Huge Files

But if the file is huge, for instance bigger than 300MB?
Using editors with huge files become difficult.
The solution is to split the file and when the procedure is finished, join the split files again.
To split you can you use cutf, a simple command line tool.
For help, just type cutf.

To append the files back, you can use:
On linux:
  cat file_to_append >> file_to_join  
On windows:
  type file_to_append >> file_to_join  

That's it.



Final checking

rental=# \c postgres
You are now connected to database "postgres".
postgres=# create database rental with template = template0 owner = postgres encoding = 'utf8';
CREATE DATABASE
postgres=# \c rental
You are now connected to database "rental".


rental=# show client_encoding;
client_encoding
-----------------
UTF8
(1 row)


rental=# show server_encoding;
server_encoding
-----------------
UTF8
(1 row)


rental=# select * from category;
cod_category | description
---------------+-------------------
1 | ação
2 | aventura
3 | biográficos
4 | comédia
5 | drama
6 | épicos
7 | espionagem
8 | fantasia
9 | ficção científica
10 | ficção histórica
11 | guerra




Attempt using iconv

Dump the database:
pg_dump -U postgres rental > rental/rental.dbs.out

Convert it to utf-8 with iconv:
iconv --from-code latin1 --to-code utf-8 rental/rental.dbs.out > rental/rental.dbs.out.utf8

Drop the old latin1 database:
dropdb rental

Created the new utf-8 database:
psql -U posgres
create database rental with template = template0 owner = postgres encoding = 'utf8';

Restore the converted backup:
psql -U postgres rental < rental/rental.dbs.out.utf8

>Before
postgres=# \l
List of databases
Name | Owner | Encoding
----------------+----------+----------
rental | postgres | LATIN1


rental=# select * from category;
cod_category | description
---------------+----------------------
1 | ação
2 | aventura
3 | biográficos
4 | comédia
5 | drama
6 | épicos
7 | espionagem
8 | fantasia
9 | ficção científica
10 | ficção histórica
11 | guerra

>After
rental=# \l
List of databases
Name | Owner | Encoding
----------------+----------+----------
rental | postgres | UTF8

rental=# select * from category;
cod_category | description
---------------+-------------------------------------------
1 | aÃ\u0083§Ã\u0083£o
2 | aventura
3 | biogrÃ\u0083¡ficos
4 | comÃ\u0083©dia
5 | drama
6 | Ã\u0083©picos
7 | espionagem
8 | fantasia
9 | ficÃ\u0083§Ã\u0083£o cientÃ\u0083­fica
10 | ficÃ\u0083§Ã\u0083£o histÃ\u0083³rica
11 | guerra

Tuesday, August 23, 2011

slf4j issues on JEE projects

The following errors have something in common - the slf4 library.




Each of them are commented, and probably you can find if your problem fits to one of them.




Example #1
SLF4J: Class path contains multiple SLF4J bindings.Criação inicial do objeto SessionFactory falhou. Erro: java.lang.NoSuchMethodError: org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;

This is really simple to solve.
Search for two versions of slf4 libraries, like this:
project/lib/slf4j-api-1.6.1.jar
project/lib/slf4j-api.jar
Delete one of them, preferably the one which does not have the version number.

Example #2 - Running on Eclipse
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/servers/jboss-5.1.0.GA/common/lib/slf4j-jboss-logging.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/servers/jboss-5.1.0.GA/client/slf4j-jboss-logging.jar!/org/slf4j/impl/StaticLoggerBinder.class]



If the jar files listed above are not inside the project, try to find if you have some duplicated reference on the project's properties, like Build Path (Source,Project and Library tabs), Targeted Runtimes, etc.


For instance, if you have a reference to another project that also contains the same libraries, they'll conflict. The pictures below show a conflict between the project and the referenced project, the one added on Project tab.
You can have the same issue on the Library tab, if you added libraries from a server, for example.
Following the red arrows. Click over the picture to zoom.







The eclipse console will show an error message like this:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/alsdias/work/dev/servers/jboss-5.1.0.GA/common/lib/slf4j-jboss-logging.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/alsdias/work/dev/servers/jboss-5.1.0.GA/client/slf4j-jboss-logging.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.



If everything seems to be fine, but the problem is still there, the fastest way to solve a "ghost" reference is to create a new project, importing the code again.

Example #3
Hibernate: select nextval ('hibernate_sequence')
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource;
at org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172)



Usually happens due incompatibilities with the project's library and the slf4 version.
Using annotations, this problem was solved switching these versions:
slf4j-api-1.5.10.jar
slf4j-simple-1.5.0.jar

by this one:
slf4j-api-1.6.1.jar


Example #4
17:39:03,260 INFO Configuration:1547 - Configured SessionFactory: null
...
anything else here



The 4th example leads us to a false conclusion - that the problem occurred due a null SessionFactory.
This is a common message and it is usually logged by the application during successful procedures, as shown in the example below,
which shows the output generated by a simple insertion of an entity on the database table.
Sometimes, it's the last message to be generated before the exception occurrence, and so, we may think that it is the cause.

In this case, check the version of the slf4.jar used on the project.
If using annotation, try this version:
slf4j-api-1.6.1.jar

Conclusion:
If you're getting these kinds of errors, try another version for your slf4..jar  before trying anything else.

For more details about slf4 error/warning messages, check http://www.slf4j.org/codes.html#StaticLoggerBinder

Example of successful procedure containing the "SessionFactory: null" message:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
17:39:02,870 INFO Environment:514 - Hibernate 3.2.6
17:39:02,876 INFO Environment:547 - hibernate.properties not found
17:39:02,879 INFO Environment:681 - Bytecode provider name : cglib
17:39:02,883 INFO Environment:598 - using JDK 1.4 java.sql.Timestamp handling
17:39:02,962 INFO Configuration:1432 - configuring from resource: hibernate.cfg.xml
17:39:02,963 INFO Configuration:1409 - Configuration resource: hibernate.cfg.xml
17:39:03,260 INFO Configuration:1547 - Configured SessionFactory: null
17:39:03,576 INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
17:39:03,576 INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 20
17:39:03,577 INFO DriverManagerConnectionProvider:45 - autocommit mode: false
17:39:03,588 INFO DriverManagerConnectionProvider:80 - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/getit
17:39:03,589 INFO DriverManagerConnectionProvider:86 - connection properties: {user=postgres, password=****}
17:39:04,480 INFO SettingsFactory:89 - RDBMS: PostgreSQL, version: 8.3.7
17:39:04,481 INFO SettingsFactory:90 - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 8.4 JDBC3 (build 701)
17:39:04,661 INFO Dialect:152 - Using dialect: org.hibernate.dialect.PostgreSQLDialect
17:39:04,692 INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
17:39:04,706 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
17:39:04,707 INFO SettingsFactory:143 - Automatic flush during beforeCompletion(): disabled
17:39:04,708 INFO SettingsFactory:147 - Automatic session close at end of transaction: disabled
17:39:04,708 INFO SettingsFactory:154 - JDBC batch size: 15
17:39:04,708 INFO SettingsFactory:157 - JDBC batch updates for versioned data: disabled
17:39:04,710 INFO SettingsFactory:162 - Scrollable result sets: enabled
17:39:04,711 INFO SettingsFactory:170 - JDBC3 getGeneratedKeys(): enabled
17:39:04,711 INFO SettingsFactory:178 - Connection release mode: auto
17:39:04,713 INFO SettingsFactory:205 - Default batch fetch size: 1
17:39:04,713 INFO SettingsFactory:209 - Generate SQL with comments: disabled
17:39:04,717 INFO SettingsFactory:213 - Order SQL updates by primary key: disabled
17:39:04,717 INFO SettingsFactory:217 - Order SQL inserts for batching: disabled
17:39:04,718 INFO SettingsFactory:386 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
17:39:04,721 INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
17:39:04,722 INFO SettingsFactory:225 - Query language substitutions: {}
17:39:04,722 INFO SettingsFactory:230 - JPA-QL strict compliance: disabled
17:39:04,723 INFO SettingsFactory:235 - Second-level cache: enabled
17:39:04,723 INFO SettingsFactory:239 - Query cache: disabled
17:39:04,723 INFO SettingsFactory:373 - Cache provider: org.hibernate.cache.NoCacheProvider
17:39:04,729 INFO SettingsFactory:254 - Optimize cache for minimal puts: disabled
17:39:04,730 INFO SettingsFactory:263 - Structured second-level cache entries: disabled
17:39:04,741 INFO SettingsFactory:283 - Echoing all SQL to stdout
17:39:04,741 INFO SettingsFactory:290 - Statistics: disabled
17:39:04,741 INFO SettingsFactory:294 - Deleted entity synthetic identifier rollback: disabled
17:39:04,744 INFO SettingsFactory:309 - Default entity-mode: pojo
17:39:04,744 INFO SettingsFactory:313 - Named query checking : enabled
17:39:04,817 INFO SessionFactoryImpl:161 - building session factory
17:39:05,361 INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into public.test (name, id) values (?, ?)

Monday, August 15, 2011

Base de Dados de CEP em MySQL, PostgreSQL e Dicas Adicionais

NOTE:
English is the usual language here on the purpose to increase sharing possibilities once it is an international language, however the information here is just about some specific brazilean stuff - the CEP, our USPC, so it was written in the native language.

Por esses dias andei precisando criar massa de dados em vários bancos com o propósito de testar performance e funcionalidades de uma aplicação. Quando esbarrei com a necessidade de carregar as tabelas de dados de CEP, naveguei a Internet por um longo período, encontrando todo tipo de informação menos o que eu realmente precisava - a base de dados do CEP.
Uma nota de indignação geral foi comum na maioria dos sítios(sites), reclamando o direito de obter-se o material de domínio público.
Afinal, o CEP até 2000, ainda era cedido sem restrições, posteriormente perdendo tal característica quando alterou o nome para DNE - Diretório Nacional de Endereços, segundo informação encontrada em http://www.vextenso.com.br/blog/55/banco-de-dados-com-os-ceps-do-brasil-retrocesso.html

Finalmente, em uma segunda tentativa inconformada, encontrei a informação necessária em http://republicavirtual.com.br/cep/index.php, cujo download fica  aqui.

Eu gostaria de agradecer o gesto do colega e o ótimo trabalho, tomando a liberdade de multiplicar tal gesto fazendo referência também aqui, no blog, e adicionando uma versão alternativa para PostgreSQL e MySQL.

Você pode encontrar os arquivos no link abaixo, já que aqueles que foram postados na nuvem sempre acabavam deletados.

https://ultering.com/it4us/Base de dados


DICAS

1. Disponibilizei um link alternativo dessa base original em MySQL(cep_mysql_sql.7z), com a alteração a seguir:
 `tp_logradouro` varchar(20) DEFAULT NULL,
foi alterado para
 `tp_logradouro` varchar(30) DEFAULT NULL,
devido a mensagem de erro ocasionado por campo maior em uma das tabelas.
O restante funcionou perfeitamente.

2. A versão em PostgreSQL foi dividida em arquivos menores e as linhas longas  foram quebradas em linhas menores, uma por registro.

Se o link estiver quebrado ou indisponível, mande um email para (alsdias@yahoo.com.br).

Essa alteração tem dois objetivos:
a) facilitar a edição do arquivo pois do contrário o editor fica pesado, lento.
b) facilitar também a localização de erros em eventuais mensagens de erro geradas pelo compilador do SGDB, pois percorrer um registro por linha é mais prático do que super extensas linhas, além de deixar o editor mais leve.


Se desejar, você pode executar as partes como se fossem um único arquivo criando um script que as referencie. É uma operação simples de inclusão de caminhos (paths).


Alternativa à Atualizaçao da Base de Dados

Em muitos sites encontrei a reclamação da dificuldade de atualizar a base pois o arquivo mdb estaria criptografado e só permite consultas manuais pela interface.

Nem tanto, você pode decodificar o arquivo mdb fazendo uma leitura binária e ter acesso à informação. Depois é só utilizar o famoso Ctrl+F (find) do seu editor, e lá está o que você deseja. Depois é só Ctrl+C e Ctrl+V.

O executável é um pequeno aplicativo em C(BinReader.tar.gz)  que faz este serviço para que se possa atualizar a base.

Basta digitar "BinReader.exe path_do_mdb".
O pequeno programa, embora simples, vai gerar um arquivo texto de leitura direta, apesar de "sujo", mas a informação pertinente é legível.

É um código simples, criado rapidamente para atender consultas que ficariam exclusivas pela interface gráfica, mas que transformadas em texto podem ser percorridas também por qualquer programa, ou manualmente, colhendo-se a informação complementar desejada.

NOTA:
Se houver link quebrado, mande um email para (alsdias@yahoo.com.br).


Tuesday, July 5, 2011

debian workspace switching fails


If you try to switch your workspaces with the usual shortcuts (ctrl+alt+F..) and it fails, try to set a new one.

Go to debian menu, system, preferences, keyboad shortcuts.
You're gonna find an action denoted by "Switch the workspace ...".
Create a new shortcut but make sure that it's not used for any other action on your environment.


Ctrl-A fails on Debian


The Ctrl+A shortcut is by default used to "select all" procedures.
If you try a "all text selection" on an editor and the command fails, test the Ctrl key with other combinations, for instance Ctrl+C and Ctrl+V (copy/paste).
If Ctrl key is working properly and that just happens with Ctrl+A, probable it's because there is a shortcut conflict.

Go to debian menu, system, preferences, keyboad shortcuts.
Check which shortcut is using the "Ctrl+A and disable it (click over the shortcut column, and use backspace - see note on the window).

If the shortcut disabled is important for you, switch to another combination that it's not used yet.


eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...