Hospedagem Profissional

Hospedagem Profissional
Clique aqui e ganhe US$ 10,00 para testar durante 1 mês a melhor hospedagem: Digital Ocean!

domingo, 6 de dezembro de 2015

Linux: Enviando e-mails com sSMTP pelo GMail

Depois de dois dias batendo cabeça para habilitar o envio de e-mail em um dos meus servidores Ubuntu 14.04.3 com o sSMTP, utilizando uma conta do Gmail, decidi fazer esse post para quem sabe ajudar futuros aventureiros.

Vamos lá!

1 - Instalando o sSMTP:


sudo apt-get install ssmtp

2 - Configurando o STMP do Gmail e suas credenciais:


sudo nano /etc/ssmtp/ssmtp.conf

O arquivo ssmtp.conf ficou assim:


#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
# root=postmaster

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
# mailhub=mail

# Where will the mail seem to come from?
# rewriteDomain=

# The full hostname
#hostname=

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES

hostname=localhost
Root=usuario@gmail.com
Mailhub=smtp.gmail.com:465
RewriteDomain=gmail.com
AuthUser=usuario #(sem o @gmail.com)
AuthPass=sua_senha
FromLineOverride=Yes
UseTLS=Yes

OBS. Não esqueça de colocar os seus dados nos parâmetros "Root", "AuthUser" e "AuthPass". O resto fica como no exemplo.

3 - Instalando o cliente de envio de e-mail para que você possa enviar mensagens pelo PHP, via scripts bash, diretamente no console, etc.


sudo apt-get install heirloom-mailx

4 - Testando o envio! Para isso, execute no console:


echo "Teste de envio de e-mail pelo gmail com sSMTP" | mail -s "Teste de e-mail" destinatario@seudominio.com

OBS. Não esqueça de trocar "destinatario@seudominio.com" pelo seu e-mail.


E se o e-mail de teste não chegar ?

Bom, é aqui que perdi 2 dias da minha vida pra fazer isso funcionar.

É problema de REDE ou de CONFIGURAÇÃO ?

Para isso, use o telnet :


# telnet smtp.gmail.com 465
Trying 173.194.212.108...
Trying 173.194.212.109...
Trying 2607:f8b0:400c:c11::6d...
telnet: Unable to connect to remote host: Network is unreachable

Se a resposta for parecida com o quadro acima, seu problema é de rede.

- Verifique se o seu provedor tem algum tipo de bloqueio anti spam para envio de e-mails por SMTP (No meu caso utilizo DigitalOcean e eles bloqueiam por padrão, tive que abrir um ticket no suporte para que pudessem habilitar. Perdi horas por conta disso achando que eu tinha configurado algo errado).

- Verifique se existe alguma regra de firewall impedindo que o seu servidor se conecte no SMTP do Gmail na porta configurada (no caso deste post, a porta utilizada foi a 465). Para isso, dê uma olhada nas regras do IPTABLES ou UFW. Se usa provedores que tem uma camada de segurança extra como a Amazon Web Services por exemplo, veja no painel de controle na parte de segurança se tem algo impedindo o acesso.

Resolvidas essas questões, o que se espera do telnet é algo assim:


# telnet smtp.gmail.com 465
Trying 173.194.212.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.

Agora repita o teste de envio relatado no passo 4 acima. Se ainda assim não receber o e-mail, seu problema é de configuração ou de prevenção de invasão do Google.

Primeira coisa, veja no log do seu servidor os detalhes das tentativas de envio:


# tail -n 100 /var/log/mail.log 

Se o resultado for algo como abaixo, seu problema é usuário ou senha errados (confira bem), ou algum dispositivo de prevenção de invasão do Google:


Nov  7 01:33:34 lion sSMTP[28075]: Creating SSL connection to host
Nov  7 01:33:35 lion sSMTP[28075]: SSL connection using RSA_ARCFOUR_SHA1
Nov  7 01:33:35 lion sSMTP[28075]: Authorization failed (534 5.7.14  https://support.google.com/mail/answer/78754 y194sm2932906vkd.13 - gsmtp)

Se tem certeza que seu usário e senha estão corretos, verique se o Gmail não te mandou algum e-mail lhe informando uma possível invasão de conta, como o seguinte:


Esse problema me tomou mais algum tempo, até que eu pudesse perceber o e-mail na caixa de entrada. Clique em "Revisar seus dispositivos agora" e confirme sua identidade.

Ainda sobre o Google, mesmo que não receba o e-mail acima, certifique-se de:
Foi no primeiro item do check list que perdi horas achando que meu problema era alguma configuração. Veja do que se trata :

Para proteger sua conta, o Google pode dificultar o login à sua conta se suspeitar que ele não esteja sendo feito por você. Por exemplo, o Google pode solicitar informações adicionais, além do seu nome de usuário e sua senha, se você estiver viajando ou se tentar fazer login na sua conta em um novo dispositivo.
Sendo assim, acesse o link https://g.co/allowaccess e caso esteja bloqueado, libere o acesso a novos dispositivos para sua conta. Esse era o meu problema, e depois de liberado, fiz o teste de envio novamente e veio a mensagem esperada no log:


Nov  7 01:50:30 server sSMTP[28123]: Creating SSL connection to host
Nov  7 01:50:30 server sSMTP[28123]: SSL connection using RSA_ARCFOUR_SHA1
Nov  7 01:50:33 server sSMTP[28123]: Sent mail for destinatario@gmail.com (221 2.0.0 closing connection p138sm2945424vkd.25 - gsmtp) uid=0 username=root outbytes=603

E é claro, recebi o e-mail de teste na minha caixa de entrada.

Uma última observação: Nas minhas pesquisas, identifiquei que algumas pessoas tiveram problemas com os certificados para acesso via SSL.
Para isso, algumas propriedades adicionais foram utilizadas no arquivo ssmt.conf, sendo:


UseStarTTLS=Yes
TLS_CA_File=/etc/ssl/certs/ca-certificates.crt

Bom, espero ter ajudado. Se tiver algo a acrescenter, comente o post.

domingo, 29 de novembro de 2015

Apache Camel 2.16 - Swagger Java and API documentation out of the box

Este vídeo mostra a utilização do Apache Camel, com CDI e Swagger para geração de documentação automática para serviços rest.

In the upcoming Apache Camel 2.16 release we recently added a pure Java based Swagger module, camel-swagger-java.

This module is replacing the older camel-swagger module that was Scala based. The new module is also using the new swagger 2.0 spec. And least but not least the module integrates out of the box, so end users just need to turn it on, by declaring the context-path to use for servicing the Swagger API documentation. Then Camel is able to auto detect camel-swagger-java on the classpath and tie into the swagger model read and generate the API as swagger 2.0 in json format. All this can be run in any kind of JVM. You do not need to use a servlet container (but you can).




Fonte: http://www.davsclaus.com/2015/09/apache-camel-216-swagger-java-and-api.html

domingo, 15 de novembro de 2015

Como rodar JSF 2.2 no JBoss AS 7.1.1.Final "Brontes"

Esse tutorial tem por objetivo apresentar os passos necessários para a atualização do JBoss AS 7.1.1.Final "Brontes" para que seja possível rodar aplicações utilizando o JSF 2.2.

Vamos lá!

O primeiro passo é efetuar o download dos jars de 'impl' e 'api' do Mojarra 2.2

Para isso, use as urls abaixo :


No momento em que escrevo esse post, as últimas versões são:


Coloque o jar de 'impl' na seguinte pasta:

<jboss_home>/modules/com/sun/jsf-impl/main

Edite o arquivo 'module.xml' nesse diretório e altere o atributo 'resource-root-path' para o nome do jar de 'impl' que você copiou. No nosso caso, 'jsf-impl-2.2.12.jar'.

A versão final do XML ficou assim:


<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.sun.jsf-impl">
    <properties>
        <property name="jboss.api" value="private"/>
    </properties>

    <dependencies>
        <module name="javax.faces.api"/>
        <module name="javaee.api"/>
        <module name="javax.servlet.jstl.api"/>
        <module name="org.apache.xerces" services="import"/>
        <module name="org.apache.xalan" services="import"/>
    </dependencies>

    <resources>
        <resource-root path="jsf-impl-2.2.12.jar"/>
        <!-- Insert resources here -->
    </resources>
</module>


Agora coloque o jar de 'api' na seguinte pasta:

<jboss_home>/modules/javax/faces/api/main

Edite o arquivo 'module.xml' nesse diretório e altere o atributo 'resource-root-path'para o nome do jar de 'api' que você copiou. No nosso caso, 'jsf-api-2.2.12.jar'.

Ainda no arquivo 'module.xml', adicione a linha abaixo na seção 'dependencies':


<module name="com.sun.jsf-impl"/>

A versão final do XML ficou assim:


<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="javax.faces.api">

    <dependencies>
        <module name="javax.el.api" export="true"/>
        <module name="javax.servlet.api" export="true"/>
        <module name="javax.servlet.jsp.api" export="true"/>
        <module name="javax.servlet.jstl.api" export="true"/>
        <module name="javax.validation.api" export="true"/>
      <module name="com.sun.jsf-impl"/>
    </dependencies>

    <resources>
        <resource-root path="jsf-api-2.2.12.jar"/>
        <!-- Insert resources here -->
    </resources>
</module>

Pronto, seu JBoss está rodando JSF 2.2.


segunda-feira, 9 de novembro de 2015

Getting Started With Docker

The De Facto Open-Source Containerization Solution


Teaches you typical Docker workflows, building images, creating Dockerfiles, and includes helpful commands to easily automate infrastructure and contain your distributed application


quarta-feira, 26 de agosto de 2015

Top Ten Use Case Mistakes

Welcome to the third in a series of five articles that provides a prepublication look at the annotated example from the forthcoming book, Applied Use Case Driven Object Modeling(Addison-Wesley, 2001; tentatively scheduled for April). We're following the process detailed in our first book, Use Case Driven Object Modeling with UML (Addison-Wesley, 1999), as we dissect the design of an Internet bookstore. In this article, we show common mistakes, and then explain how to correct them.
Within the ICONIX process, one of the early steps involves building a use case model. This model is used to capture the user requirements of a new system (whether it's being developed from scratch or based on an existing system) by detailing all the scenarios that users will perform. Use cases drive the dynamic model and, by extension, the entire development effort.
Figure 1. The "Big Picture" for Use Case Driven Object Modeling
The diagram portrays the essence of a streamlined approach to software development that includes a minimal set of UML diagrams and some valuable techniques that take you from use cases to code quickly and efficiently.
Figure 1 shows where use case modeling resides within the "big picture" of the ICONIX process.

The Key Elements
The task of building use cases for your new system is based on immediately identifying as many as you can, and then establishing a continuous loop of writing and refining the text that describes them. Along the way, you will discover new use cases, and also factor out commonality in usage.
You should keep one overriding principle in mind during your effort to identify use cases: They should have strong correlations with material found in the system's user manual. The connection between each use case and a distinct section of your user guide should be obvious. It reinforces the fundamental notion that you are designing a system that will conform to the viewpoints of the users. It also provides a convenient summary of what "use case driven" means: Write the user manual, then write the code. If you're reengineering a legacy system, you can simply work backward from the user manual.
Once you have some text in place for a use case, it's time to refine it by making sure the sentences are clear and discrete, the basic format of your text is noun-verb-noun, and the actors and potential domain objects are easy to identify. You should also update your domain model—the subject of our previous article, "Driving Design: The Problem Domain" (Jan. 2001)—as you discover new objects and expand your understanding of the objects you'd previously found. And, it's important to determine all possible alternate courses of action for each use case wherever possible, an activity which should take up the majority of the time.
You can use several mechanisms to factor out common usage, such as error handling, from sets of use cases. This is usually effective, because breaking usage down to atomic levels will ease the analysis effort and save you lots of time when drawing sequence diagrams. Whether you use UML's generalization and includes and extends relationships, or OML's invokes andprecedes relationships, which we recommend in our book, your goal should be a set of small, precise, reusable use cases.
You should feel comfortable proceeding to the next phases of the development process when you've achieved the following goals:
  • You've built use cases that together account for all of the desired functionality of the system.
  • You've produced clear and concise written descriptions of the basic course of action, along with appropriate alternative courses of action, for each use case.
  • You've factored out scenarios common to more than one use case, using whichever constructs you're most comfortable with.

The Top 10 Use Case Modeling Errors
Contrary to the principles we just discussed are a number of common errors that we have seen students make when they're doing use case modeling on their projects for the first time. Our "top 10" list follows.

10. Don't write functional requirements instead of usage scenario text. Requirements are generally stated in terms of what the system shall do, while usage scenarios describe actions that the users take and the responses that the system generates. Eventually, our use case text will be used as a run-time behavioral specification for the scenario we'll describe, and this text will sit on the left margin of a sequence diagram. We want to be able to easily see how the system (shown with objects and messages) implements the desired behavior, as described in the use case text. So, we need to clearly distinguish between usage descriptions (behavior) and system requirements.

9. Don't describe attributes and methods rather than usage. Your use case text shouldn't include too many presentation details, but it should also be relatively free of details about the fields on your screens. Field names often match the names of attributes on your domain classes, which we discussed in January's article. Methods shouldn't be named or described in use case text because they represent how the system will do things, as opposed to what the system will do.

8. Don't write the use cases too tersely. When it comes to writing text for use cases, expansive is preferable. You need to address all of the details of user actions and system responses as you move into robustness analysis and interaction modeling, so you might as well put some of those details in your use cases. Remember also that your use cases will serve as the foundation for your user manual. It's better to err on the side of too much detail when it comes to user documentation.

7. Don't divorce yourself completely from the user interface. One of the fundamental notions of "use case driven" is that the development team conforms the design of the system to the viewpoints of the users. You can't do this without being specific as to what actions the users will perform on your screens. As we mentioned for item number nine, you don't need to talk about fields in your use case text, and you don't want to discuss the cosmetic appearance of your screens; however, you can let your prototypes, in whatever form they take, do that work for you. You do need to discuss those features of the user interface that allow the user to tell the system to do something.

6. Don't avoid explicit names for your boundary objects. Boundary objects are the objects with which actors will interact. These frequently include windows, screens, dialogs and menus. In keeping with our theme of including ample detail and being explicit about user navigation, we submit that it's necessary to name your boundary objects explicitly in your use case text. It's also important to do this because you will explore the behavior of these objects during robustness analysis (the subject of the next article in this series), and it can only reduce ambiguity and confusion to name them early.

5. Don't write in the passive voice, using a perspective other than the user's. A use case is most effectively written from the user's perspective as a set of present-tense verb phrases in active voice. The tendency of engineers to use passive voice is well-established, but use cases should state the actions that the user performs, and the system's responses to those actions. This kind of text is only effective when it's expressed in the active voice.

4. Don't describe only user interactions; ignore system responses. The narrative of a use case should be event- response oriented, as in, "The system does this when the user does that." The use case should capture a good deal of what happens "under the covers" in response to what the actor is doing, whether the system creates new objects, validates user input, generates error messages or whatever. Remember that your use case text describes both sides of the dialog between the user and the system.

3. Don't omit text for alternative courses of action. Basic courses of action are generally easier to identify and write text for. That doesn't mean, however, that you should put off dealing with alternative courses until, say, detailed design. Far from it. In fact, it's been our experience that when important alternative courses of action are not uncovered until coding and debugging, the programmer responsible for writing or fixing the code tends to treat them in ways that are most convenient for him. Needless to say, this isn't healthy for a project.

2. Don't focus on something other than what is "inside" a use case, such as how you get there or what happens afterward. Several prominent authors, such as Alistair Cockburn and Larry Constantine, advocate the use of long, complicated use case templates. Spaces for preconditions and post-conditions are generally present on these templates. We like to think of this as the 1040 "long form" approach to use case modeling, in comparison to the 1040EZ-like template that we advocate (two headings: Basic Course and Alternate Course). You shouldn't insist on using long and complex use case templates just because they appeared in a book or article. 

1. Don't spend a month deciding whether to use includes or extends. In our years of teaching use case driven development, we've yet to find a situation where we've needed more than one mechanism for factoring out commonality. Whether you use UML's include construct, or OML's invoke and precede mechanisms, or something else that you're comfortable with, doesn't matter; simply pick one way of doing things and stick with it. Having two similar constructs is worse than having only one. It's just too easy to get confused—and bogged down—when you try to use both. Don't spin your wheels. 
Figure 2 shows use case text that contains violations of five of the top 10 rules.
Did you spot the violations?
  • Use case one is too terse. There is no reference to what kind of information the customer enters, nor to the page he or she is looking at. The text doesn't explain what is involved in validating the data that the customer entered. And the use case doesn't describe how the customer needs to respond to an error condition.
  • Use case two doesn't have explicit names for the relevant boundary objects.
  • Use case three reveals how useless it can be to obsess about using a complicated use case template. The name of the use case expresses the goal clearly enough; the content of the basic course will make the stated precondition and postcondition redundant.
  • Use case four lacks alternate courses, even though it should be fairly clear from the context that some validation needs to occur, and that there are several possible error conditions (for instance, the system can't find the e-mail address, or the password that the customer entered doesn't match the one that is stored).
  • Use case five doesn't specify how the system responds when the customer presses the update button.

Figure 3 shows the use case text with the mistakes corrected.
Our next article will demonstrate how to do robustness analysis in order to tighten up use cases and make it easier to head into detailed design. See you next month.

Figure 2. The 1040 "Long Form" Approach to Use Cases
Use case text that contains violations of five of the top 10 rules.

Figure 3. The 1040EZ Approach to Use Cases
The use case text with the mistakes corrected.

Fonte: http://www.drdobbs.com/top-ten-use-case-mistakes/184414701

sexta-feira, 27 de março de 2015

Write an SOA integration layer with Apache Camel

Web services integration with Spring and Apache Camel

Ótimo artigo da Java World sobre a utilização do Apache Camel como integrador de serviços.

-------------------***-------------------



In this Java tip, learn how to use Apache Camel to develop a quick-and-easy integration layer for a service-oriented architecture. Apache Camel lets you configure Camel integration components for web service endpoints; message transformation, routing, and aggregation; and exception handling. All with a minimum of Java coding.

Introduction


Integration is a top priority for enterprise projects that seek to connect multiple web service endpoints quickly, efficiently, and maintainably. From a development standpoint, integration can also be a serious challenge. One way to ease that challenge is by using an integration framework like Apache Camel.


Apache Camel's API and out-of-the-box components implement many common enterprise integration patterns (EIPs), making it relatively simple and easy to do integration tasks such as connecting web services, performing XSL transformations, logging audits, and more. In this Java tip we introduce a process for using Apache Camel as an integration solution. We start with a business integration problem involving multiple web services. We then map the problem, briefly discuss the components needed to resolve it, and implement a solution based on Apache Camel's routing engine.

Flow diagram of an SOA architecture


sábado, 28 de fevereiro de 2015

Escolha o mais importante - trabalhe menos e entregue mais! Princípio de Pareto


Na Europa do final do século 19, o ainda jovem italiano Vilfredo Federico Damaso Pareto nutria um fascínio por questões ligadas ao poder e à riqueza. Como as pessoas faziam fortuna ou ganhavam poder? Como a riqueza era distribuída na sociedade?
Aos 40 anos, já formado engenheiro civil, Pareto resolveu se dedicar seriamente a responder a essas questões, enveredando para a economia.
Em 1906, constatou que apenas 20% da população da Itália tinha 80% das propriedades. Também verificou que 20% dos pés de ervilha de seu jardim davam 80% das ervilhas. Por meio de muitas observações semelhantes, análises e cálculos, formulou as bases do que, alguns anos depois, seria batizado de Princípio de Pareto, ou Princípio 80/20.
“É a observação de que um número pequeno de eventos gera a maioria dos efeitos”, afirma o inglês Richard Koch, autor do livro Os Segredos do Gerente 80/20, lançado em maio pela editora Objetiva. “Poucas coisas realmente importam, mas as que importam fazem muita diferença.
”A consciência do desequilíbrio é algo pouco natural para o homem. Em geral, pensamos em distribuir as coisas de maneira uniforme. A teoria de Pareto mostra que a assimetria predomina no mundo e que é importante considerá-la nas análises. “Depois que descobrimos o quão desequilibrado é o nosso mundo, podemos passar a tirar vantagem dele”, diz Koch.


O universo dos negócios e do trabalho também não escapa da regra do 80/20. “Os gerentes pensam que todas as receitas geram lucros porque pensam na média.” Koch critica a maneira como as empresas lidam com os clientes.
“Uma das mais perigosas e idiotas, ainda que duradouras, suposições do mundo corporativo é a de que toda receita é valiosa e todas as fontes de receita têm mais ou menos a mesma importância. Elas não têm. Um cliente não é tão bom quanto outro. Um segmento não é tão bom quanto outro.”
No mundo do trabalho, o princípio tem a mesma força. A maioria dos gerentes opera no mundo das médias. O resultado? “A vida profissional conspira para corrermos atrás de inúmeros objetivos irrelevantes que gastam nossa energia sem nunca nos dar o que realmente queremos”, afirma Koch.
Em outras palavras, deveríamos descobrir o que realmente é importante e faz a diferença em nossas atividades em vez de distribuir a energia por todas as tarefas. Quem tem a percepção de como o princípio rege as relações de trabalho e dos negócios em geral trabalha melhor.
Não que todo mundo conheça a regra do 80/20, mas há pessoas que notam o desequilíbrio e, ao usar isso no dia a dia, conseguem priorizar e focar aquilo que realmente vai trazer os maiores resultados. O importante é encontrar sua combinação única de baixo esforço e alto resultado.

Como conteúdo adicional, abaixo segue um ótimo vídeo chamado "Gestão do Tempo com o Princípio 80/20 (Pareto)" do canal "Gerenciar o Tempo Agora".


Outro vídeo muito bom, onde o Evandro Mazuco do "Gerenciar o Tempo Agora" dá 3 dicas para aumento de produtividade que achei bem interessantes:
  1. Técnica dos 50 minutos
  2. Princípio do 80/20 (Pareto)
  3. Técnica do Progresso Constante
Veja o vídeo com a explicação de como utilizar estas 3 dicas ao seu favor, vale a pena!



Mais informações em : http://www.gerenciarotempoagora.com.br

sexta-feira, 27 de fevereiro de 2015

Primefaces lança Layout e Tema "Sentinel"

Em resumo, é esse meu sentimento em relação ao tema Sentinel

O Primefaces lançou no dia de hoje, 27/02, o tema e layout Sentinel, com licença Premium.

O objetivo é apresentar uma aplicação 100% responsiva utilizando componentes do Primefaces, e como não poderia deixar de ser, o padrão de qualidade não poderia ser melhor.

Como a licença é Premium, existe um custo. E você pode escolher comprar somente o tema, ou o tema + layout.

Na licença regular (onde o produto final é gratuito), o Tema + Layout sai a US$79 e somente o Tema sai a US$ 49.

Over 100 JSF Components, Responsive, Html 5 & CSS 3, 
Font-Icons, Pixel-perfect Design, Ajax Framework

Veja o vídeo de divulgação:

Vale por MIL palavras

Características:


Responsive Layout

  • Clean and Powerful 
  • Ready to Use 
  • Mobile Optimized
  • Awesome Design

HTML 5 & CSS 3 Scripting

  • HTML 5 & CSS 3 based Transitions
  • Fonts
  • Effects and more

Cross-Browser Compatibility

  • Safari
  • Chrome
  • Firefox
  • Opera
  • Internet Explorer 9+

Sentinel Theme

  • All components are styled to be compatible with the Layout Design for a unified look 

Font-Icon Support

  • With Font Awesome 
  • Fontello icon fonts
  • Custom icons

Pixel-Perfect Design

  • Clean Design
  • Production Ready
  • Well Tested

Mais informações: