Mostrando postagens com marcador Wicket. Mostrar todas as postagens
Mostrando postagens com marcador Wicket. Mostrar todas as postagens

24 janeiro 2014

Hackathon de Java e Raspberry Pi na CPBr14


Você que é desenvolvedor Java e vai para a Campus Party na semana que vem de 27 de Janeiro a 2 de Fevereiro de 2014, não pode perder o Hackathon de Java e RaspberryPi promovido pelo SOUJava, com apoio da Oracle, trazendo kits, premiação, e mentoring! O objetivo é aprender, praticar e inovar, e todos os participantes ainda vão ganhar uma camiseta. Um dos projetos será selecionado para apresentação no palco principal!

Presença de grandes nomes da comunidade Java brasileira como:

Para maiores informações, consulte o site do SOUJava Hackathon de Java e Raspberry Pi na Campus Party.

11 novembro 2013

Reality of Open Source Users in Mobile and Cloud Era

- "I built my Android app entirely with Open Source products, both in the app, and in the backend server running on Amazon. I'm charging US$ 1,99 for it in the Google Play Store" 
- "That's wonderful! Where is the source code of your app? Have you contributed back to these Open Source products? Will you release your product as Open Source?"

In this new era of Cloud Computing and Mobile apps, there's an increasing number of for-profit products that takes advantage of Open Source products, but barely contribute anything back to them, either by buying support, or non-expensive things such as reporting bugs, fixes, or helping documentation. Developers are building SaaS applications for Salesforce.com, or Mobile apps for Android and iOS devices, and usually charge for these. Of course, they want to make money as anyone else.

Whenever I ask someone that makes money with _their_ software built on top of Open Source, if they will ever release the source code, they usually answer: "my case is different". Well, why is your case different? Why can't I buy your app from Google Play Store, and still access the code on GitHub? Or build it on my own, customize it, etc? That's the point of Open Source, right? Wrong, in their minds.

Majority of software developers actually tend to think that Open Source is free as in free beer. And that's it. No matter how hard you try to explain otherwise, the industry will almost always see Open Source software as free software. And due to the new way to sell software, I really think that Mobile apps and Cloud SaaS/PaaS offers will, sooner or later, kill good Open Source softwares, and leave this space only for conceptual and initial implementations for Open Standards and APIs, or for general use and development platforms and languages such as Java, Ruby, etc.

Perhaps you want to read Will Cloud kill Open Source? Is the Future Open Standards? Your thoughts are welcome :-)

10 setembro 2013

Java SE 7 update 40 e o Mission Control 5.2

Java SE Downloads
Chegou uma nova atualização do Java SE 7: update 40. Esta versão inclui várias novas funcionalidades como o Java Mission Control, Deployment Rule Set, suporta para o Retina display no Mac, e suporte a Hard Float ABI no Linux ARM v7. Também inclui diversas correções de bugs. Para quem desenvolve Applets e aplicações Java Web Start, este release, fica a atenção para conhecer e enteder as mudanças.

Deployment Rule Sets

Esta funcionalidade permite um administrador de desktops a controlar o nivel de compatibilidade para clientes Java assim como níveis de segurança para a empresa. Para maiores detalhes, veja a documentação do Deployment Rule Set.

Java Mission Control

O Mission Control era até então uma ferramenta disponível para clientes Oracle, e que foi lançada há muito tempo atrás junto com o JRockit (JRMC). Mas a Oracle agora disponibilizou a ferramenta junto com a JRE HotSpot 7u40. 

Esta ferramenta permite monitorar, gerenciar, introspectar, e detectar memory leaks nas suas aplicações Java, sem ter que introduzir códigos para isso, que normalmente degradam a performance da aplicação. Hoje esta ferramenta está agora disponível no download do Oracle HotSpot JDK 7u40!

Flight Recorder

Mas a principal e mais importante característica é o Flight Recorder. Este recurso funciona através da leitura de eventos produzidos pela JVM. Mesmo ativando a geração destes eventos, a sobrecarga total  para as suas aplicações ainda fica abaixo de 2%, que considerando o tipo e o valor de informação que você recebe, é quase nada. Um exemplo de evento é a chamada de um método de uma classe Java.

Com o profile de chamadas de métodos você pode descobrir onde o aplicativo está gastando a maior parte do tempo executando seu código Java. Este é, por exemplo, útil para otimizar a aplicação onde as otimizações realmente terão impacto. Isto sem precisar introspectar seu código manualmente!

Alem disso, você tem também uma visão de otimização para alocação de objetos. Você pode ver por exemplo, a alocação em tempo real de objetos na Old Gen da memória heap. diretamente no espaço de idade, além de outras abas que oferecem diversas informações importantes sobre o processamento de informações na sua aplicação Java. Leituras de arquivos I/O, Socket I/O e muito mais.

Se você precisa de mais informações sobre o Mission Control, entre na página da ferramenta em www.oracle.com/missioncontrol.

E obrigado ao Markus Eisele por ter cedido parte deste post! :-)

22 fevereiro 2013

Encontro SouJava na Oracle (JMS e Cache Distribuido)

No dia 21 de Fevereiro estreamos o novo escritório da Oracle abrindo as portas para o grupo de usuários do SouJava. Com a presença do Bruno Souza, Ricardo Ferreira, Edgar Silva, Vinicius Senger, Mauricio Leal e muitos outros, tivemos a participação ao todo de 26 pessoas.

Durante a reunião, apresentei As Novidades do JMS 2.0, parte importante do Java EE 7 e que teve votação do Public Review no dia 19/02. O SouJava votou a favor, não só pela qualidade mas também pela transparência da especificação.

A outra apresentação foi do Ricardo Ferreira, falando sobre Processamento de Dados em Memória usando Elastic Data Grid (In-Memory Computing), que demonstrou a importância do uso de cache distribuído em arquiteturas altamente escaláveis, com o Oracle Coherence.

No final, os participantes conheceram o novo escritório da Oracle e ainda foram muito bem recebidos com muita pizza. Confira as fotos do evento!

04 janeiro 2013

Issue dev'ing RESTful JSON services on NetBeans


Here is a tricky issue that you may find if you are developing RESTful services with Java EE on NetBeans and GlassFish or WebLogic. If you want to support the JSON format but need to access some implementation classes like @JsonIgnore, you need to add the JAX-RS RI, Jersey, to your project's Libraries definition. How to add the RI? You will probably do this:
  1. Open project's Properties (right click on the project)
  2. Go to Libraries
  3. Click on 'Add Library'
  4. Select 'Jersey 1.8 (JAX-RS RI)
But you won't have your service running fine. You may find these exceptions: (added here so Google can help future users)
1 - If you try to access your RESTful service to get a JSON format of it, you will get this exception:
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
  at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
  at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
2 - If you try to access your RESTful service to get an XML format, you will get this exception:
java.lang.RuntimeException: javax.naming.NameNotFoundException: Unable to resolve 'com.sun.jersey.config.CDIExtension'. Resolved 'com.sun.jersey.config'; remaining name 'CDIExtension'
  at com.sun.jersey.server.impl.cdi.CDIExtension.getInitializedExtension(CDIExtension.java:177)
  at com.sun.jersey.server.impl.cdi.CDIComponentProviderFactory.(CDIComponentProviderFactory.java:92)
  at com.sun.jersey.server.impl.cdi.CDIComponentProviderFactoryInitializer.initialize(CDIComponentProviderFactoryInitializer.java:75)
  at com.sun.jersey.spi.container.servlet.WebComponent.configure(WebComponent.java:576)
  at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.configure(ServletContainer.java:311)
 If you look at your server's log, (in my case, I was using WebLogic 12c) you may find this message somewhere:
WARNING:
**********
The application is using ServletContainerInitializer class com.sun.jersey.server.impl.container.servlet.JerseyServletContainerInitializer that is loaded from:file:/labs/wls1211/modules/com.sun.jersey.server_1.1.0.0_1-9.jar. This initializer overrides the one available in the system.
**********
When you added Jersey to your library, the "package" checkbox was checked by default. So the JAR ended up going into WEB-INF/lib of your project, conflicting to the already provided by the container. 
So, how to fix this issue? Follow these steps:
  1. Open project's Properties (right click on the project)
  2. Go to Libraries
  3. Uncheck the checkbox 'Package' for Jersey 1.8 (JAX-RS RI)
  4. Click on 'OK'
  5.  Clean & Build (right click on the project) ---> remember to clean and rebuild your project
  6. (re)Deploy application
Done! :_)
https://blogs.oracle.com/brunoborges/entry/issue_dev_ing_restful_json

09 agosto 2011

Participações em eventos de 2011

O ano de 2011 está agitado para mim.

Já estive no JustJava, no The Developers Conference (edição São Paulo) e na próxima semana estarei presente no TDC Florianópolis. Em Setembro ainda tenho o QCon, evento do InfoQ-Caelum. E sobre o quê tenho falado? Apache Wicket.

O desenvolvimento Web em Java deixou de ser lento, e nestas minhas palestras, apresento uma proposta diferente. Programadores e Web Designers trabalhando em conjunto sem que um prejudique ao outro.

Foi-se o tempo que a separação de camadas se dava apenas na programação. Chegou a hora de separar também o trabalho do designer e o do programador. Afinal, o web designer é quem entende bem de CSS, efeitos, web fonts e UX.  No meu post "What are web frameworks missing?" detalho melhor este tema.

Mas voltando aos eventos, segue a programação para quem quiser saber mais:

The Developers Conference - edição Florianópolis
Data: 20 de Agosto de 2011 - 13:10 na trilha Java
saiba mais


QCon - São Paulo
Data: 10 de Setembro de 2011 - 18:10
saiba mais

E se quiser se aprofundar mais, confira o Curso de Apache Wicket que lancei este mês. O curso começa no dia 4 de Setembro.

Curso de Apache Wicket

Lancei ontem o Curso de Apache Wicket, para iniciantes e para aqueles que já utilizam. O curso será ministrado online através de uma ferramenta com compartilhamento de tela e chat. Serão ao todo 4 aulas com duração de 3 horas e meia.

Durante o curso, os alunos construirão uma aplicação completa, integrada ao Spring, paginação e outras funções em Ajax. Os interessados podem se inscrever pelo site www.cursodewicket.com.

Valor: R$ 389,00


4 de Setembro: 9:30 - 13:00
11 de Setembro: 9:30 - 13:00
18 de Setembro: 9:30 - 13:00
25 de Setembro: 9:30 - 13:00

12 julho 2011

What are web frameworks missing?

First of all: there's no perfect web framework. And it doesn't matter what technology, language or platform. But I finally have come to one thing that is really important. Something most web frameworks are missing, and something I believe, as many other developers that have already blogged about, is the future of the Web.

Let's start with the consequence of the problem: the infinit fight between Web Designers and Web Developers. Designers and developers have been fighting for years within web development. And this happens because the work done by designers usually is "destroyed" by developers when they have to inject dynamic/logical code into the HTML, converting it to something like JSP, PHP, RHTML or a mix of Python and HTML. It doesn't matter the language.

The problem is clear: what the designer did goes away. If he must update the design, even if the data structure won't change, most certainly you will have problems. He might break some logics, some code, and you will have to fix it. Then, you might also break some layouts and he will have to fix it. And you might go into a loop for a couple of days because of something that should be done in about hours.


We all talk about separating layers. But when it comes to designers vs developers, we really don't care about because we are trying to push an idea of programmers that are able to design just like designers, or designers able to code as programmers. That just won't happen. You may find one or two excellent professionals like that, but is not easy. Developers and designers have different way of thinking. The former has artistic creativity while the later has logical criativity. So if we, developers, are always saying "let's use the right tool for the right job", what's happening with the designer? His work is not being done in the right tool. I've seen designers with IDEs installed on their Macs because they have to run the project to see how it's looking like.

What if he could simply use Coda or Dreamweaver or TextMate as he does but then just preview the damn HTML in the browser, which is the right tool for him? What if he could simply preview the code that will actually be send to the client? What if he could... do his work with the best tools available? The best tool for his job.

I believe in and code with a Web Framework that helps both Developers and Designers to execute their tasks with the best tools they know. A developer should concern on data, on logic, on security. A designer should concern on layout, design, colors, UX. And what one does should not break the work done by the other.

Without mixing dynamic code with HTML, or even worse, replacing HTML elements with Tag Libraries (JSP, JSF and others), the designer can just open the HTML in the browser and see how is the prototype.

You know that prototype your designer has worked on for a week to get approval from your customer? You can just use that with minimal changes, and the prototype can still be statically functional and also run in the server. If you get an email asking for a change in the layout, no problem. Ask your designer to change the HTML, he will preview in the browser, get approval from the customer, and your developer won't have to change a line.

This is what Web Frameworks are missing. This is what I'd like to see implemented in any Web Framework. This is what Apache Wicket is providing.

The rest is just scaffolding, templates and code generation.

The future is of course static HTMLs, JavaScript and REST+JSON. Web frameworks are dead.
But until the future comes, let's just improve the web development process a little bit, shall we?

11 dezembro 2010

Top 10 reasons why I don't like JSF

At this JavaOne Brasil, there was a great discussion about Java Web Frameworks, with folks from Caelum, GlobalCode and Oracle. Arun Gupta, Maiko Rocha, Vinicius and Yara Senger, and many others who came to participate.

The discussion went mostly around what companies and developers should do before choosing a Web Framework. Although I was willing to move the discussion to another level (eg, poiting these 10 reasons), I decided to just take it easy. And as I stated: there's no perfect Web Framework. But there's a perfect web framework for your case.

But now I think it is the right time and place to share my thoughts. Here are my top 10 reasons (mostly non-technical) on why I don't like JSF.
  1. Extra step when defining a project's architecture
    People insist on comparing JSF with other frameworks. They should stop doing that. You can compare MyFaces to RichFaces to Tapestry to Vaadin to GWT. JSF is a specification, not a final product.

    Vendors too insist on marketing JSF as a Web Framework. But they forget to mention that you will be locked-in to their implementation because of lots and lots of non-standard components. It ain't cool.

    You spend a week comparing *one* JSF implementation with other frameworks, and if you chose JSF, you then realize you have an extra step: you have to pick a vendor, an implementation, and then goes another week of POCs, tests and evaluations. And you'll be locked. It is not easy to move from one to another. Specially when you have to use those non-standard components to turn your project on something really functional.

  2. Fragmented Community
    Now, let's say you, developer, works on a project for 6 months, on top of RichFaces. Then you move to another project built on top of MyFaces. Yes, you will have to sign in to another mailing list. To another forum. Different from other products, JSF has no centralized community. If you are working with Wicket, you go to users@wicket.apache.org. If you are working with VRaptor, you go to their Forum. If you are working with JSF, you will need to sign up for at least 3 different mailing lists, sign up for 3 forums and probably, tens of blogs.

    It is not easy to ask for help on a fragmented community. If you face a problem with RichFaces, when you were used to work with ICEFaces, you might end up asking something stupid, and probability is you will be told of a different solution to the same problem.
     
  3. Fragmented Documentation
    If community is important, imagine documentation. You must have bookmarks of all JSF implementations. If you work with GWT, you need only one. If you work with SpringMVC, just go to springframework.org. Also there's the problem of non-standard components. Let's say you are working with Seam, and you have to bind some component to some RichFaces component. Where will you find a documentation about that? There's no such thing. If you are luck, you might find some blog post on Google. Odds you won't find. You will discover by yourself after hours of debugging and tracing, and in the end, you will not blog about that too. You will just move on.

  4. Component Incompatibility
    Well, there's not much to say on this. JSF 2.0 address some issues, but not all of them. Component interoperability between different components can't be easily documented because of JSF's nature. This (documentation) also happens on some non-standard frameworks, but there are others that the core architecture helps a lot the developer to just don't care about this. Wicket is one of them. Components are grained and independent. If you want to interoperate different components, you simply share a Model or deal with events.

  5. Caveats on some scenarios because of different implementations
    This one I heard from a JSF developer. He said RichFaces fires rendering updates in a different way to MyFaces Trinidad. If the developer must be aware of that, odds are you won't find proficient JSF developers.

    I pointed about this one at the Web Frameworks discussion at JavaOne. It is not easy to find a Wicket developer, or a Vaadin developer. But when you find them, probability is they will be proficient, or at least above regular web developers.

    With JSF, which has tons and tons of job offers around the world, but lots of implementations and caveats, probability is that you will easily and quickly find a JSF developer to hire, but he or she won't be proficient. They will be regular developers. I'm not saying this is 100% true. Of course it is possible to find a proficient JSF developer. But with different implementations, it is hard to find one that knows all about of their tricks, tips, issues and secrets.

  6. Designers and developers roles mixed
    Oracle said it has set up JDeveloper or some other inside tool with JSF support to their web designers. Now, this is cool. You teach web designers to define templates, UIs, using the Java IDE. In the end you have the view done and all JEE devs need to do is to bind, code and run.

    This is one way of doing it. But usually, it is not the case. Most companies have Web Designers working on Mac, with Photoshop and Dreamweaver or some other WYSIWYG editor. They are great designers partly because of great tools.

    With JSF, designers and developers mix their work. Designers spend their time templating. Developers spend most of their time fixing broken templates after mixing them with JSF components. Now this, ain't cool at all.

  7. Does not improve usual web development process
    Like I said before, companies are still working with a development process based on: design, template, inject dynamic code, fix design issues, release.

    That's how Java Web development works. If you disagree, please comment on that. But I've been developing web applications for almost 8 years and that's how I see it.

    All frameworks that mix dynamic code on the HTML or some layer that outputs it, doesn't improve the common web development process. Which sucks, IMO. You have Web Designers to do all the prototype. Sometimes, your company pays to a Design shop to do that. And in the end, you have business developers fixing design issues because a pixel here or there is not correctly aligned with that right border.

    Now, there are some frameworks that address this issue quite well. Tapestry is one of them, if not the first. Then there's Wicket, which of course the best practice is to componentize the UI, but it is possible to work only with the prototype. With JSF, you have Facelets. It helps a lot, and I'm sure improves *a bit*. But the development process is beyond working with pure HTMLs and prototypes.

    With JSF, the developer does a lot of SOP - String Oriented Programming. If you are not working with a great JSF-supported IDE, you will end up doing a lot of copy-paste of Strings of method names, property names and bean names.

    Some may argue that Wicket replaces JSTL with Java. It is true. But consider this: if you are working with Wicket and you've already binded your UI, you don't have to look to your HTML again. With JSF, you must look at your ManagedBean and your page to make sure everything is correctly binded. On Wicket, new properties and methods can be added without modifying the UI, and still with JSF you must edit two files to do that. It is one approach, I know. But that does not changes neither improves the development process if you compare to Struts. GWT improves that, just as Wicket, IMO.
     
  8. Non-functional prototype
    Ok, not a big deal. But it sucks a lot when your web designer changes the UI and you must merge those changes. What if you had a functional prototype you can share with your Web Designer? Some frameworks do that. Tapestr and Wicket for example. The output is HTML, your are building HTML, your designer gives you HTML, so why not take advantage of that work done on a previous stage?

  9. Performance
    Just Google for benchmarks comparing JSF with any other Java Web Framework. The lifecycle is just huge.... :-(
     
  10. Web is fast, standards are slow
    Let's take JPA for example. How old is SQL? Since 1974. Hibernate was build based on something that it was already a standard. So it was JPA. It is reasonable to have a specification for that, and totally acceptable to work with. JPA developers won't have problems dealing with different implementations, at least if they do their job right. What about XML frameworks? Mid 90's. My point is. Some specifications are build based on something with limited scope, even though generic, or on something that is already a standard and well-know by the market.

    Now let's take the Web. Although HTML is a specification, and old, it definitely has an unlimited scope. And because of its nature, it is open to innovation and creativity. How to standardize that?! HTML5 is almost there, and we are still waiting for a specification that really improves the Web Development Process. Again, JSF2 is a huge step forward, but too late, and just like to what happened with EJB, people are now afraid of it because its previous version. And that's why people started to choose Rails, Python, GWT and other frameworks.

    Long learning curve. Slow improvements (thanks to JCP). Everything the Web does not need. Everything Agile methodologies are against to.
I did work with JSF before, and I love to be a Java developer. I have my work done with it, and I'm paid because of it. But I felt like being left behind while looking at friends building cool apps, quickly and with good quality, with other languages, other platforms. And if I want to deliver solutions with performance, quality AND speed to my customers, I will think twice before choosing JSF.

Sure it has scenarios or business strategies where JSF is the best option. If there wasn't, Oracle/Sun, IBM, Red Hat and others would not put money on that. For companies that want to make sure they will easily and quickly find a developer to replace another, to keep the work on a JSF project, then, it's a business decision.

Now, from a developer perspective, I prefer to do my projects with something non-standard, while the Web is not standardized, and my customers are not worried about that.

16 novembro 2010

Tutorial: Começando com Apache Wicket (Parte I)

Já que não tem Apache Wicket no JavaOne Brasil, vai um tutorial de Apache Wicket, entitulado "Começando com Apache Wicket (Parte I)" publicado no Lado Servidor, com o apoio do Paulo Jerônimo e da wdev, que contribuíram para minha participação no The Developers Conference 2010, em Florianópolis. O bacana desse tutorial é que produzi um video também, para acompanhar (sem cortes) o desenvolvimento da aplicação de exemplo.

Curioso em saber como ficou o resultado? Então vai logo ver.

Tutorial: Começando com Apache Wicket (Parte I)

E se você perdeu a Trilha Web do TDC 2010 e não viu minha palestra, confira ao menos os slides.

Apache Wicket derruba o padrão JSF

[]'s
Bruno

09 novembro 2010

ApacheCon Brazil and why we need it?


I'm not sure if this mailing list is the right one to write about this, but I'm gonna take the risk. I suppose "Community" means anything related to it. And this is definitely about community.

Before anything, I'd like to share my history with ASF. (skip if you want... :D)

When I started to get involved with the Apache Software Foundation in a deeper level, I was still just a user, downloading Tomcat and using it. I guess most Java developers for the Web environment still do that.

5 years a go, I joined the Apache Wicket community and then my relationship with ASF has born. And for the last 5 years I've been speaking about it in Brazil, either in JUG meetings or at conferences around the country and sharing everything I wanted to share on my blog. I've even created a Google Groups for that, called Wicket pt_BR. With my contributions as an "evangelist" I gave birth to friendships with great people like Martijn Dashorst, Jeremy Thomerson, Eelco Hillenius and others from the Wicket community.

Then, in 2008 I heard about the Apache TAC and, thanks to ASF, I could meet them in person during ApacheCon @ New Orleans. It was better than anything I've ever experienced. Considering how close I was to great people, professionals and friends, and how easy I could start chatting about anything to them, I thought that was the best conference it could ever exist. I thought: "ApacheCon is the best. I got free beer!". That was cool. Every conference I go here in Brazil, I wish someone put some beers instead of Coke. Until now... only #fail

Then, right after I came back from New Orleans, I started to play with the SOA stack (CamelCXFServiceMix and ActiveMQ). I also became friend of great people like Bruce Snyder, Claus Ibsen, Hadrian Zbarcea and Debbie Moynihan.

Last year, 2009, when I heard about ApacheCon in San Francisco, I took the chance to apply again to the Apache TAC (no, I wasn't bargaining; it really is expensive to fly from Brazil to the USA, specially SF). I just applied for the tickets, and for accommodation I was safe with CouchSurfing friends I already knew. Also, I really wanted to help the organization. It was when I met Nick Burch, Ross Gardler and Noirin Shirley. Could not forget my latin friends Amelia Blevins and Carlos Sanchez. Other names like Jesse McConnell, David Blevins and Yeliz Eseryel are also in my good memories of ApacheCon 2009. Unfortunately this year, because of personal reasons (not because of TAC rules), I couldn't be present at ApacheCon.

With the help of Bruno Souza, I discussed with some people, including Sally Khudairi, the idea of bringing ApacheCon to South America.

What I saw on ApacheCon '08 and '09 was something amazing. Perfect for South America. Perfect for Brazil. The Apache Way is something that must be shared with everyone. 

A few months a go, I went to Brasilia (country's capital) to talk about the ASF in general, not on an specific project. It's amazing how people are unaware of what the ASF really is. And how people limit their knowledge to only what the big players show to them. Still, they all know Struts and Tomcat. It seems that South America is a big user of Apache projects rather than truly contributors.

Now this year, with JavaOne going to happen in Brazil, and the sessions that were scheduled, I believe it is now the time to drive ApacheCon south. There's no single talk about anything related to the Apache Software Foundation in this South American version of JavaOne. And I feel really sad about that. Sad that people that are behind the organization had the opportunity to accept papers (I myself proposed Wicket and Camel - papers I have been presenting since 2008 for rooms of 30~40 attenders).

And I'm sure everyone will use Maven, Ant or Tomcat to demonstrate something.

I don't know if this happened because of recent issues between Oracle and Apache, or just because of Java standards (like JSF, JavaFX, EJB) are more important than non-standard projects. It doesn't matter. I'm sure there was room. On my count, there are at least 3 subjects with more than 1 submission approved. Look at JavaOne track.

Now, if the ASF, the most voted JCP EC member (with 95% votes), has no space on JavaOne Brazil, the country who have been participating in the Open Source movement, giving birth to the OpenJDK thanks to Javali project, and Bruno Souza, than we should start considering other alternatives. Alternatives to standards, like Wicket or Camel.

We already have ApacheCon Europe and North America. I'm sure we can do ApacheCon South America.

Let's do this happen. Let's do it the Apache way.

Bruno Borges

05 novembro 2010

Apache Wicket ainda mais divertido: Parte 1

Este é o primeiro de uma série de artigos para mostrar o Wicket à comunidade brasileira. Cada artigo que eu ler sobre JSF, Facelets e afins que achar interessante e me questionar: "seria ainda mais divertido fazer isso com Wicket", vou fazer um "fork" do artigo e codificá-lo com o Apache Wicket.

Para começar, vou forkar o artigo do Eder Magalhães sobre como tornar um trecho de código Facelets em um componente reutilizável, chamado "Facelets ainda mais divertido! Parte II".

[início do fork]
Neste post vou comentar sobre a criação de componentes usando somente HTML simples e Java puro - na minha opinião o grande diferencial do Wicket. O cenário é um formulário de manutenção de registros de funcionários, e o protótipo é simples:
É comum um protótipo ser entregue por Web Designers, e o nosso trabalho está em adaptar aquele protótipo para processar informações dinâmicas. A página acima se chama CadastroFuncionarios.html e a seguir, o código que o Web Designer entregou:

CadastroFuncionarios.html

Mas é comum ter trechos de telas que são repetitivos. Como os botões de ações deste formulário. Então é interessante tornar isso um componente para ser reutilizado e quando exigir modificação, que seja apenas uma vez, em um único lugar.

No Wicket, páginas são componentes, e funcionam em pares (Java e HTML). Como queremos construir um componente com os botões, precisamos de um painel, para ser reutilizado em outras páginas. O primeiro passo é criar a classe e um HTML exclusivo para o painel, contendo somente os componentes de botão.

Para criar um novo painel para agrupar componentes, existe a classe Panel. Vamos criar uma subclasse dela e especializá-la:

BarraBotoes.java

Por se tratar de um painel de botões, deixei implementado 3 métodos associados 1 para cada botão. Quem utilizar este componente, poderá facilmente sobrescrever estes métodos para adicionar funcionalidades por ação. Outra vantagem aqui está na documentação gerada automaticamente, se o programador preencher o Javadoc.

Para finalizar o componente (segunda etapa), é preciso o HTML do painel, chamado de BarraBotoes.html

BarraBotoes.java

A tag wicket:panel é uma das poucas tags especiais (carregadas pelo DTD). Aqui ela serve para delimitar o que representa o painel, sem prejudicar as ferramentas WYSIWYG. Deixei propositalmente o restante do código HTML por fora da tag para representar um protótipo, que pode ser visto pelo designer e ajustado por ele próprio, caso queira mudar folhas de estilo. A vantagem é que ele pode avaliar se estas mudanças atenderão os requisitos de design. Ou seja, o protótipo continua funcional. Também foi feito o binding entre os componentes no HTML e os componentes em Java através do atributo wicket:id.

A partir desse momento, o painel pode ser reutilizado. Nenhuma outra configuração é necessária. Exceto um import da classe em outras páginas. :-)

Agora precisamos ajustar a página que conterá o painel. Abaixo, o novo HTML da página CadastroFornecedores.html já com os ajustes para binding com Wicket:

CadastroFuncionarios.html

E o código Java para a página:

CadastroFuncionarios.java

Para implementar uma ação, o programador precisa somente sobrescrever os métodos que lhe for necessário. Agora que a página está pronta, e utilizando o componente, o próximo passo é melhorar a inteligência do componente, com zero de alterações nos HTMLs, poucos ajustes na classe do painel BarraBotoes, e uma linha de alteração na classe da página.

  • Apresentar o botão excluir de forma condicional, com base em um boolean
  • Botão cancelar deve sempre abortar o formulário onde estiver contido

Caso seja de interesse do programador acrescentar mais lógica no componente, para que por exemplo os botões tenham visibilidade condicional, ajustes na classe BarraBotoes devem ser feitos. E somente nela. No HTML nada precisa ser alterado. Abaixo, o código da classe com lógica de visibilidade condicional de botões:

BarraBotoes.java

A primeira acao foi adicionar um construtor que recebesse um Model (assunto para outro post), do tipo Boolean, e associar este Model como condicional para o método isVisible() do botão excluir.

A segunda ação foi ajeitar o construtor padrão para continuar funcionando como anteriormente, e mantendo assim compatibilidade com páginas que sempre mostram o botão excluir. Novas páginas poderão utilizar o novo construtor e condicionar a exibição do botão, se quiserem.

A terceira ação foi cancelar o processamento dos dados do form quando o botão cancelar for clicado. Para isto, a propriedade defaultFormProcessing deve ser desabilitada.
[fim do fork]

A grande vantagem do Wicket está em jogar para o lado Java toda a programação da interface, deixando o protótipo limpo, estático, e mesmo assim permitindo o programador manipular com uso inteligente da orientação a objetos, os componentes de tela.

O que mais você gostaria de saber sobre o Wicket?

Abraço,
Bruno

PS: mock de tela feito no Mockflow

21 março 2010

Wicket Brasil: mais de 600 mensagens


Em 2008, ainda trabalhando para a Summa Technologies, que conheci o framework Apache Wicket. Isso aconteceu porque meu amigo Michael Nascimento sugeriu o Wicket como possível base para um módulo web do Genesis. O módulo não saiu, mas meu interesse pelo framework só aumentou. Naquele mesmo ano, em Setembro, apresentei o Wicket à galera do JustJava, junto com o Claudio Miranda. A sala estava cheia e muita gente curiosa em conhecer o framework web mais divertido do momento. É tão divertido desenvolver com ele, que o título da palestra ficou até óbvio. Por fim, em outubro de 2008 nascia a comunidade Wicket em Português.

Após 1 ano e meio, já foram mais de 600 mensagens pelo grupo, e a cada semana recebo pelo menos um pedido de inscrição. Vejo que, assim como aconteceu com Struts em 2002, acontece agora com Wicket.

Para acelerar o crescimento dessa comunidade e difundir o conhecimento do framework a todos os desenvolvedores, deixo aqui avisado que, se você tiver um evento de Java, um JUG ou uma empresa que pretende trabalhar com Java para a Web, entre em contato e eu estarei presente para apresentar o Apache Wicket.

E que em 2010 o número de mensagens passe de mil !!

15 junho 2009

Curso de Wicket

Uma das coisas boas da comunidade Java é a vontade que muitas pessoas tem em contribuir com a própria comunidade. O Cristiano Kliemann, um dos membros da Wicket-pt_BR mostrou isso ao disponibilizar o material do Curso de Wicket que ele ministrou há algum tempo atrás.

Tenho certeza que este material será de grande valia para muita gente.

Valeu Cristiano!

06 novembro 2008

RESTful Web Services with Wicket


Here at ApacheCon, with the help of Jeremy Thomerson I could finally finish an idea I had months ago. How to easily provide simple RESTful Web Services with Wicket?

Basically, I wanted to output an Object as an XML with XStream. And the result is this simple class that you can extend and just have to provide a model with an object inside. Whatever is inside the model, gets outputted. :-)

So take a look at the class and use it as you wish.

package org.wicketstuff.wicketws;

import java.io.PrintWriter;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.IBehavior;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebPage;

import com.thoughtworks.xstream.XStream;

/**
* RESTful WebSevice page
*/
public abstract class WebServicePage extends WebPage {

private static final long serialVersionUID = 1L;

public WebServicePage() {
setStatelessHint(true);
}

protected final void onRender(MarkupStream markupStream) {
PrintWriter pw = new PrintWriter(getResponse().getOutputStream());
pw.write(getXML().toString());
pw.close();
}

protected XStream createXStream() {
XStream xstream = new XStream();
xstream.setMode(XStream.ID_REFERENCES);
return xstream;
}

private CharSequence getXML() {
XStream xstream = createXStream();
return xstream.toXML(getDefaultModelObject());
}

@Override
public final String getMarkupType() {
return "xml";
}

@Override
public final boolean hasAssociatedMarkup() {
return false;
}

@Override
public final Component add(IBehavior... behaviors) {
throw new UnsupportedOperationException(
"WebServicePage does not support IBehaviours");
}

}

And here's a quick example of a WebService:

package org.wicketstuff.wicketws;

import org.apache.wicket.PageParameters;
import org.apache.wicket.model.Model;

public class UserInfo extends WebServicePage {

public UserInfo(PageParameters pg) {
Integer id = pg.getAsInteger("id");
if (id == null) {
id = 1;
}

User user = ((WicketApplication) getApplication()).getUser(id);
setDefaultModel(new Model(user));
}

}

Oh, and don't forget to mount your WebService to get the default URL Strategy that is REST-like in Wicket.

@Override
protected void init() {
mountBookmarkablePage("userInfo", UserInfo.class);
}

Now all you have to do is access http://localhost:8080/myapp/userInfo/id/1

Done!! :D

22 outubro 2008

Atualize-se para o Wicket 1.3.5


Atualize-se! Versão 1.3.5 do Apache Wicket já está disponível nos repositórios Maven, assim como em formato eager. :-)

Essa versão traz, obviamente, bugs corrigidos (90+) e novas funcionalidades e melhorias (30+). A série 1.3 do Wicket é para aqueles que ainda não migraram para o uso com Generics; este somente na série 1.4. Veja aqui a nota desta nova versão, com a lista dos problemas/melhorias corrigidos/implementadas.

Então, se você quer atualizar seu projeto para a nova versão, basta editar seu pom.xml e colocar:
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket</artifactId>
<version>1.3.5</version>
</dependency>


Se você não usa Maven, não tem problema. Clique aqui para ter a versão eager.

Ainda na versão 1.2?!? Migra logo!!

[]'s!!
Bruno

10 outubro 2008

Convertendo valores financeiros no Wicket

É muito comum a necessidade de se converter valores no desenvolvimento Web. E quando precisamos disso, é importante que o framework aplicado no projeto possua uma facilidade enorme para que a solução desta necessidade não se torne em um pesadelo.

No Apache Wicket, muitas conversões são já automáticas, graças aos conversores-padrão. Mas, às vezes é necessário customizar alguns destes conversores para algo mais específico. Como a conversão de valores monetários, por exemplo. E a boa notícia é que, apesar de existirem 3 formas de se obter o mesmo resultado, todas elas são fáceis de serem implementadas e cada uma possui a sua utilidade.

A primeira e mais objetiva é prover um conversor customizado, reaproveitando-se de um já existente, a um componente específico:

        PropertyModel pm = new PropertyModel(pojo,
"valor");

add(new Label("valor1", pm) {
public IConverter getConverter(Class type) {
return (IConverter) new BigDecimalConverter() {
public NumberFormat getNumberFormat(Locale locale) {
return NumberFormat.getCurrencyInstance(locale);
}
};
}
});


A segunda, é criar um conversor customizado para poder reutilizá-lo em outros componentes:

public class BigDecimalCurrencyConverter extends BigDecimalConverter {

public NumberFormat getNumberFormat(Locale locale) {
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
return format;
}

}


        add(new Label("currency2", new Model(new BigDecimal("99"))) {
public IConverter getConverter(Class type) {
return (IConverter) new BigDecimalCurrencyConverter();
}
});


E a terceira opção, um pouco mais complexa, consiste em definir um tipo para valores monetários, , um conversor específico para este tipo e registrar este conversor na aplicação Wicket, para que sempre que este tipo passar por algum componente, será automaticamente convertido. Vamos ver como fica.

Como não se pretende aqui sobrescrever o conversor padrão para BigDecimal, cria-se o tipo Currency:

public class Currency extends BigDecimal {

public Currency(BigDecimal value) {
super(value.toString());
}

}


Isto serve para que, em lugares onde não se quer definir literalmente um valor monetário, mas apenas um BigDecimal, seja posssível utilizar-se do BigDecimalConverter, fornecido automaticamente pelo framework. Sem conflitos! :-) Agora é preciso definir o CurrencyConverter:

public class CurrencyConverter extends AbstractDecimalConverter {

private BigDecimalConverter converter = new BigDecimalConverter() {
public NumberFormat getNumberFormat(Locale locale) {
return CurrencyConverter.this.getNumberFormat(locale);
}
};

public NumberFormat getNumberFormat(Locale locale) {
return NumberFormat.getCurrencyInstance(locale);
}

protected Class getTargetType() {
return Currency.class;
}

public Currency convertToObject(String value, Locale locale) {
return new Currency(converter.convertToObject(value, locale));
}

}


Talvez você se perguntou "porque não herdar de BigDecimalConverter?". Simples: por causa de algumas definições de Generics, não é possível herdar de BigDecimalConverter, pois este já está atrelado ao tipo BigDecimal. Veja o fonte da classe. :-)

Agora, só basta registrar este conversor para o tipo Currency. Isto é feito lá na sua classe que herda de WebApplication. Sobrescreva o método newConverterLocator() desta forma:

    protected IConverterLocator newConverterLocator() {
ConverterLocator locator = new ConverterLocator();
locator.set(Currency.class, new CurrencyConverter());
return locator;
}


E pronto! Veja como fica o uso neste terceiro caso:

add(new Label("currency3", new Model(new Currency(new BigDecimal("99")))));


Agora, como utilizar isso com outros componentes além do Label, só fuçando!! Para mais informações sobre conversores, clica aqui.

Dúvidas? Sugestões? Elogios? Comentem! :-)

[]'s!

02 outubro 2008

Grupo de Discussão do Wicket, em Português


Aos desenvolvedores brasileiros e do idioma português, interessados no framework Apache Wicket, atenção! :D

Além dos canais oficiais para troca de conhecimentos:
Agora existe também o grupo de discussão Wicket em Português (wicket-ptbr). Me perguntaram porque eu não criei com o nome "Wicket Brasil". Bem, depois das mudanças na nossa Língua Portuguesa, onde o objetivo é unificar o idioma no mundo, não há mais razão para termos grupos em português específicos para o Brasil. :-) Maaaaas, brasileiro que é brasileiro, não se rende, então por isso é "wicket-ptbr" e não apenas wicket-pt!! :D

Convido a todos para participar do grupo.
Para se inscrever, acesse a página aqui.

[]'s !!

15 setembro 2008

Slides JustJava, Parte 1: Apache Wicket

Ei, você que está lendo este post, não pôde ir no JustJava este ano? Teve que trabalhar, ou então estava longe demais de São Paulo? Tudo bem.... Tuuuuudo bem. Aqui estão os slides da palestra que apresentei, juntamente com meu amigo Cláudio, sobre o Apache Wicket.

Não esperava que a sala fosse lotar. Obrigado a presença de todos vocês que compareceram. E ano que vem terá mais :-)

Ah, aos que receberam o convite para comparecer no evento, onde vocês estavam afinal? O livro sobrou... :-)

Apache Wicket @ JustJava 2008
View SlideShare presentation or Upload your own. (tags: 2008 justjava)


[]'s!

01 setembro 2008

O que mostrarei no JustJava 2008


Alguns amigos me perguntaram o que apresentarei no Just Java 2008, e depois de responder umas 3 vezes, aqui vai uma breve descrição das duas palestras que darei.

  1. Simplificando SOA com Apache CXF e ServiceMix
    Nesta que realizar-se-á na Quinta-feira (11) às 19h00, falarei sobre como o uso do ServiceMix juntamente com o Apache CXF pode simplificar a construção de uma arquitetura SOA.

    No início falarei um pouco sobre SOA, ESB e JBI. Este último não é tão conhecido. Refere-se à JSR 208, sobre Java Business Integration, e onde o ServiceMix se encaixa nisso.

    Depois, falarei mais sobre o ServiceMix e seus componentes. E então avanço para os componentes do CXF que se integram ao ServiceMix.

    Esta palestra tem o intuito de mostrar a simplicidade que é ter um WebService como ponto de entrada para o Enterprise Service Bus, e como integrar isto com outros serviços do ESB.

    Tudo bem que é a última do dia, mas... nada de ir embora cedo!! :-)
  2. Produtividade (e diversão) na Web com Apache Wicket
    Já nesta palestra, que terei a honra de compartilhar com o Cláudio Miranda, falarei sobre o framework Apache Wicket, os benefícios de se utilizar uma solução Component-based, e as características deste, que é hoje um dos frameworks mais bem vistos pelos desenvolvedores.

    A arquitetura por trás do framework, a idéia de componentização e as facilidades prontas contidas nele serão mostradas logo no início para clarear o entendimento de todos. Depois o Cláudio mostrará o lado bacana do framework, que são os componentes Ajax prontos para usar e se possível, uma demonstração.

    Esta palestra ocorrerá na Sexta-feira, às 13h00. Voltem rápido do almoço!!
Espero que vocês compareçam!!
Contato

Email:bruno.borges(at)gmail.com

LinkedIn: www.linkedin.com/in/brunocborges
Twitter: www.twitter.com/brunoborges
Comprei e Não Vou
Rio de Janeiro, RJ Brasil
Oracle
São Paulo, SP Brasil