Archive for ‘Java’ Category
Browse:
Java »
Description:

Exe?plos/Dicas em JAVA

Subcategories:

Encoding Tomcat

datePosted on 16:32, maio 26th, 2010 by Carlos Eugênio

No .bash_profile poderá inserir O ENCODING :

export LANG=pt_BR.UTF-8

No Server.xml
URIEncoding=”UTF-8″


<Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true"
    URIEncoding="UTF-8"/>

(Ajp13) can’t receive the response message from tomcat

datePosted on 13:03, maio 14th, 2010 by Carlos Eugênio

Fiz um teste de stress em meu tomcat utilizando threads e foi apresentada a seguinte mensagem:

(ajp13) Tomcat is down or refused connection. No response has been sent to the client (yet)

gerando o famoso erro de bad gateway ao acessar meu ambiente web , a primeira atitude foi reinicializar o tomcat para matar todos os processos ativos e posteriormente setar as seguintes configurações no server.xml

/opt/tomcat/conf/server.xml


<Connector protocol="AJP/1.3" port="8009" maxThreads="600"
minSpareThreads="5" maxSpareThreads="100" acceptCount="500" debug="0"
 connectionTimeout="60000" enableLookups="false"
 disableUploadTimeout="true" useURIValidationHack="false"
 redirectPort="4443" />

Funcionou direitinho , indico esta alteração nas aplicações.

[Java] – Enviando e-mail autenticado

datePosted on 15:06, maio 6th, 2010 by Carlos Eugênio

Amigos ,

Mais uma vez enfrentando os desafios do dia-a-dia me deparei com um problema teoricamente simples o envio de mensagens via e-mail , desta vez de forma autenticada ou seja informando usuário senha e conta para identificação do destinatário.

Criei a seguinte classe SendMail.java que faz este processo e segue abaixo o código :


//Class SendMail.java

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

public class SendMail {

    private static final String SMTP_HOST_NAME = "smtp.dominio";
    private static final String SMTP_AUTH_USER = "conta@dominio";
    private static final String SMTP_AUTH_PWD = "senha";
    private static final String emailMsgTxt = "Teste de Envio com autenticacao em JAVA.";
    private static final String emailSubjectTxt = "Mensagem de Teste ";
    private static final String emailFromAddress = "conta@dominio";
    // Inserir aqui os enderecos onde a mensagem sera entregue
    private static final String[] emailList = {"primeiro@dominio", "segundo@dominio", "terceiro@dominio"};

    public static void main(String args[]) throws Exception {
        SendMail smtpMailSender = new SendMail();
        smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        System.out.println("Email Enviado para primeiro@dominio e segundo@dominio e terceiro@dominio");
    }

    public void postMail(String recipients[], String subject,
            String message, String from) throws MessagingException {
        boolean debug = false;

        //Setando o host
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // Criando a mensagem
        Message msg = new MimeMessage(session);

        // Setando o endereco
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        //Conteudo
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }
}

Para funcionamento desta exemplo é necessário que utilize as jar standard.jar e mail.jar padrões do javamail.

Até Mais.

Criando pacotes DEBIAN .deb Part I

datePosted on 22:49, abril 29th, 2010 by Carlos Eugênio

Quando criamos nossas aplicacões e precisamos disponibilizá-las em ambiente de producão queremos que o processo de deploy seja o mais rápido possível. Como tornar este processo padronizado dentro de nossa empresa ?
A forma mais prática é a criacão de pacotes a forma mais difundida é são os pacotes rpm (Fedora) e deb (Debian). Neste artigo vou focar na criacão de pacotes DEBIAN os que estou estudando no momento.

O primeiro passo é preparar o ambiente instalando a seguinte ferramenta no sistema operacional DEBIAN:
sudo apt-get install devscripts fakeroot

Crie um diretório debian no /home/usuario/debian

Baixe o source do software (software.tar.gz) no diretório /home/usuario/debian

Descompacte o arquivo tar.gz em seu diretório de debian acima.

Entre no diretório gerado pelo arquivo descompactado.

Debianizando o projeto com o comando.
dh_make -e email@domantededor -f ../projeto.tar.gz

Este comando irá gerar os arquivos básicos dentro do diretório (debian) para implementacão das configuracões do pacote deb

changelog
control
copyright
dirs
docs
rules

Criando o pacote DEBIAN
dpkg-buildpackage

Instalando o pacote criado :
dpkg -i pacote

Removendo o pacote instalado
dpkg -r pacote

[OFF-Topic] 21/03/10 Corrida Batavo – ESPN 5 KM

datePosted on 22:51, março 27th, 2010 by Carlos Eugênio

Estou estreando uma nova categoria que mostra as minhas aventuras fora do mundo da informática. Pelo menos uma vez por mês participo de uma prova (corrida) de rua em São Paulo normalmente provas de 5 e 10 km.
Tenho que falar pra vocês esse hábito sadio e pelo menos 1 ano e meio atrás mudou a minha vida de me tirou do sedentarismo em que eu estava a anos.

Como prova que estou correndo segue o vídeo da chegada da última prova que fiz em 21/03/2010 eu passei por volta dos 44 minutos e 48 segundos no tempo liquido , de camiseta azul do lado direito.
Read the rest of this entry »

gem install mysql :: ERROR: Failed to build gem native extension

datePosted on 13:42, março 10th, 2010 by Carlos Eugênio

Ao publicar uma aplicação com mysql me deparei com este problema na instalação da gem mysql necessária para meu site :

gem install mysql

Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.

/usr/bin/ruby extconf.rb
can't find header files for ruby.

Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/gem_make.out

Read the rest of this entry »

Atualização do Ubuntu

datePosted on 09:44, fevereiro 18th, 2010 by Carlos Eugênio

Trabalhar com ubuntu é uma tarefa árdua estava utilizando a versão 9.04 e por questões de segurança migrei para a versão 9.10 , para variar o gerenciador de atualizações inicializava o processo e desaparecia .. Hum … tive que atualizá-lo na mão seguem os comandos quem sabe pode te safar de problemas no dia a dia.

Com usuário root :


aptitude install update-manager-core
do-release-upgrade

HANDY ONE-LINERS FOR RUBY

datePosted on 15:21, outubro 22nd, 2009 by Carlos Eugênio

HANDY ONE-LINERS FOR RUBY November 16, 2005
compiled by David P Thomas version 1.0

Latest version of this file can be found at:

http://www.fepus.net/ruby1line.txt

Last Updated: Wed Nov 16 08:35:02 CST 2005

FILE SPACING:

# double space a file
$ ruby -pe ‘puts’ < file.txt
# triple space a file
$ ruby -pe '2.times {puts}' < file.txt
# undo double-spacing (w/ and w/o whitespace in lines)
$ ruby -lne 'BEGIN{$/="\n\n"}; puts $_' < file.txt
$ ruby -ne 'BEGIN{$/="\n\n"}; puts $_.chomp' < file.txt
$ ruby -e 'puts STDIN.readlines.to_s.gsub(/\n\n/, "\n")' < file.txt

NUMBERING:

# number each line of a file (left justified).
$ ruby -ne 'printf("%-6s%s", $., $_)' < file.txt
# number each line of a file (right justified).
$ ruby -ne 'printf("%6s%s", $., $_)' < file.txt
# number each line of a file, only print non-blank lines
$ ruby -e 'while gets; end; puts $.' < file.txt
# count lines (emulates 'wc -l')
$ ruby -ne 'END {puts $.}' < file.txt
$ ruby -e 'while gets; end; puts $.' < file.txt

TEXT CONVERSION AND SUBSTITUTION:

# convert DOS newlines (CR/LF) to Unix format (LF)
# - strip newline regardless; re-print with unix EOL
$ ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' < file.txt

# convert Unix newlines (LF) to DOS format (CR/LF)
# - strip newline regardless; re-print with dos EOL
$ ruby -ne 'BEGIN{$\="\r\n"}; print $_.chomp' < file.txt

# delete leading whitespace (spaces/tabs/etc) from beginning of each line
$ ruby -pe 'gsub(/^\s+/, "")' < file.txt

# delete trailing whitespace (spaces/tabs/etc) from end of each line
# - strip newline regardless; replace with default platform record separator
$ ruby -pe 'gsub(/\s+$/, $/)' < file.txt

# delete BOTH leading and trailing whitespace from each line
$ ruby -pe 'gsub(/^\s+/, "").gsub(/\s+$/, $/)' < file.txt

# insert 5 blank spaces at the beginning of each line (ie. page offset)
$ ruby -pe 'gsub(/%/, " ")' < file.txt
FAILS! $ ruby -pe 'gsub(/%/, 5.times{putc " "})' < file.txt

# align all text flush right on a 79-column width
$ ruby -ne 'printf("%79s", $_)' < file.txt

# center all text in middle of 79-column width
$ ruby -ne 'puts $_.chomp.center(79)' < file.txt
$ ruby -lne 'puts $_.center(79)' < file.txt

# substitute (find and replace) "foo" with "bar" on each line
$ ruby -pe 'gsub(/foo/, "bar")' < file.txt

# substitute "foo" with "bar" ONLY for lines which contain "baz"
$ ruby -pe 'gsub(/foo/, "bar") if $_ =~ /baz/' < file.txt

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
$ ruby -pe 'gsub(/foo/, "bar") unless $_ =~ /baz/' < file.txt

# substitute "foo" or "bar" or "baz".... with "baq"
$ ruby -pe 'gsub(/(foo|bar|baz)/, "baq")' < file.txt

# reverse order of lines (emulates 'tac') IMPROVE
$ ruby -ne 'BEGIN{@arr=Array.new}; @arr.push $_; END{puts @arr.reverse}' < file.txt

# reverse each character on the line (emulates 'rev')
$ ruby -ne 'puts $_.chomp.reverse' < file.txt
$ ruby -lne 'puts $_.reverse' < file.txt

# join pairs of lines side-by-side (like 'paste')
$ ruby -pe '$_ = $_.chomp + " " + gets if $. % 2' < file.txt

# if a line ends with a backslash, append the next line to it
$ ruby -pe 'while $_.match(/\\$/); $_ = $_.chomp.chop + gets; end' < file.txt
$ ruby -e 'puts STDIN.readlines.to_s.gsub(/\\\n/, "")' < file.txt

# if a line begins with an equal sign, append it to the previous line (Unix)
$ ruby -e 'puts STDIN.readlines.to_s.gsub(/\n=/, "")' < file.txt

# add a blank line every 5 lines (after lines 5, 10, 15, etc)
$ ruby -pe 'puts if $. % 6 == 0' < file.txt

SELECTIVE PRINTING OF CERTAIN LINES

# print first 10 lines of a file (emulate 'head')
$ ruby -pe 'exit if $. > 10′ < file.txt

# print first line of a file (emulate 'head -1')
$ ruby -pe 'puts $_; exit' < file.txt

# print the last 10 lines of a file (emulate 'tail'); NOTE reads entire file!
$ ruby -e 'puts STDIN.readlines.reverse!.slice(0,10).reverse!' < file.txt

# print the last 2 lines of a file (emulate 'tail -2'); NOTE reads entire file!
$ ruby -e 'puts STDIN.readlines.reverse!.slice(0,2).reverse!' < file.txt

# print the last line of a file (emulates 'tail -1')
$ ruby -ne 'line = $_; END {puts line}' < file.txt

# print only lines that match a regular expression (emulates 'grep')
$ ruby -pe 'next unless $_ =~ /regexp/' < file.txt

# print only lines that DO NOT match a regular expression (emulates 'grep')
$ ruby -pe 'next if $_ =~ /regexp/' < file.txt

# print the line immediately before a regexp, but not the regex matching line
$ ruby -ne 'puts @prev if $_ =~ /regex/; @prev = $_;' < file.txt

# print the line immediately after a regexp, but not the regex matching line
$ ruby -ne 'puts $_ if @prev =~ /regex/; @prev = $_;' < file.txt

# grep for foo AND bar AND baz (in any order)
$ ruby -pe 'next unless $_ =~ /foo/ && $_ =~ /bar/ && $_ =~ /baz/' < file.txt

# grep for foo AND bar AND baz (in order)
$ ruby -pe 'next unless $_ =~ /foo.*bar.*baz/' < file.txt

# grep for foo OR bar OR baz
$ ruby -pe 'next unless $_ =~ /(foo|bar|baz)/' < file.txt

# print paragraph if it contains regexp; blank lines separate paragraphs
$ ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /regexp/' < file.txt

# print paragraph if it contains foo AND bar AND baz (in any order); blank lines separate paragraphs
$ ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /foo/ && $_ =~ /bar/ && $_ =~ /baz/' < file.txt

# print paragraph if it contains foo AND bar AND baz (in order); blank lines separate paragraphs
$ ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /(foo.*bar.*baz)/' < file.txt

# print paragraph if it contains foo OR bar OR baz; blank lines separate paragraphs
$ ruby -ne 'BEGIN{$/="\n\n"}; print $_ if $_ =~ /(foo|bar|baz)/' < file.txt

# print only lines of 65 characters or greater
$ ruby -pe 'next unless $_.chomp.length >= 65′ < file.txt
$ ruby -lpe 'next unless $_.length >= 65′ < file.txt

# print only lines of 65 characters or less
$ ruby -pe 'next unless $_.chomp.length < 65' < file.txt
$ ruby -lpe 'next unless $_.length < 65' < file.txt

# print section of file from regex to end of file
$ ruby -pe '@found=true if $_ =~ /regex/; next unless @found' < file.txt

# print section of file based on line numbers (eg. lines 2-7 inclusive)
$ ruby -pe 'next unless $. >= 2 && $. <= 7' < file.txt

# print line number 52
$ ruby -pe 'next unless $. == 52' < file.txt

# print every 3rd line starting at line 4
$ ruby -pe 'next unless $. >= 4 && $. % 3 == 0′ < file.txt

# print section of file between two regular expressions, /foo/ and /bar/
$ ruby -ne '@found=true if $_ =~ /foo/; next unless @found; puts $_; exit if $_ =~ /bar/' < file.txt

SELECTIVE DELETION OF CERTAIN LINES

# print all of file except between two regular expressions, /foo/ and /bar/
$ ruby -ne '@found = true if $_ =~ /foo/; puts $_ unless @found; @found = false if $_ =~ /bar/' < file.txt

# print file and remove duplicate, consecutive lines from a file (emulates 'uniq')
$ ruby -ne 'puts $_ unless $_ == @prev; @prev = $_' < file.txt

# print file and remove duplicate, non-consecutive lines from a file (careful of memory!)
$ ruby -e 'puts STDIN.readlines.sort.uniq!.to_s' < file.txt

# print file except for first 10 lines
$ ruby -pe 'next if $. <= 10' < file.txt

# print file except for last line
$ ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-1]' < file.txt

# print file except for last 2 lines
$ ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-2]' < file.txt

# print file except for last 10 lines
$ ruby -e 'lines=STDIN.readlines; puts lines[0,lines.size-10]' < file.txt

# print file except for every 8th line
$ ruby -pe 'next if $. % 8 == 0' < file.txt

# print file except for blank lines
$ ruby -pe 'next if $_ =~ /^\s*$/' < file.txt

# delete all consecutive blank lines from a file except the first
$ ruby -e 'BEGIN{$/=nil}; puts STDIN.readlines.to_s.gsub(/\n(\n)+/, "\n\n")' < file.txt

# delete all consecutive blank lines from a file except for the first 2
$ ruby -e 'BEGIN{$/=nil}; puts STDIN.readlines.to_s.gsub(/\n(\n)+/, "\n\n")' < file.txt

# delete all leading blank lines at top of file
$ ruby -pe '@lineFound = true if $_ !~ /^\s*$/; next if !@lineFound' < file.txt

If you have any additional scripts to contribute or if you find errors
in this document, please send an e-mail to the compiler. Indicate the
version of ruby you used, the operating system it was compiled for, and
the nature of the problem. Various scripts in this file were written or
contributed by:

David P Thomas # author of this document

Tue Jun 26 18:17:36 CDT 2007
* Thanks to Taylor Carpenter for feedback on improving redirection format.

#RailsSummit 2009 Gregg Pollack – resumo 13/10/2009

datePosted on 09:36, outubro 14th, 2009 by Carlos Eugênio

Palestra Gregg Pollack
RailsEnvy

Dicas para melhorias Rails :

>> Utilizar bullet
Avisos amigaveis para inclusão

Libraries excelentes

1 – Inserir indices na migration
>> Rails Indexes , verifica a relacao entre os modelos e indica os indices necessários.\

Configurar Controller – Otimizar

Scrooge

>> Optimize – para melhorar as consultas ao banco de dados , descobrindo os pedacos da pagina e mostra apenas os dados úteis na pagina melhorando a velocidade de execucao.

Rack-bug
>> Ferramenta de debug da aplicacao identificando consultas lentas e scripts incorretos.
>> Environment.rb >>
config middleware.use (Rack:bug)

MemoryLogic
>> Mostra as estatiticas de memoria utilizada pela aplicacao e onde está utilizando mais memória
>> Através de logs poderá ser analisado de forma mais precisa.

Oink
>> Mostra a quantidade de memória através de métricas
script/oink =threshold=0 log/development.log

Rubber

>> Vulcanizar especifica os componentes que serao utilizados : script/generate vulvanize complete_passenger_mysql , cria um arquivo chamado rubber que tem as tarefas capistrano e arquivos de configuracao , ao entrar nos diretório de configuracao os arquivos yml são apresentados e outros arq de config tb.

>> Após rodar os comandos capistrano.
>> Dynamic DNS updates >> faz os backups do ambiente de stading como o ambiente de cloud , tudo no mesmo servidor.

Auditório Lotado - Rails Summit
Acessem o twitter do cara : http://twitter.com/GreggPollack

Desinstalando o Ruby

datePosted on 10:56, setembro 25th, 2009 by Carlos Eugênio

Para remover a versão do ruby na máquina siga esses passos no terminal :

sudo rm /usr/local/bin/{ruby,irb,gem}
sudo rm /usr/local/lib/libruby-static.a
sudo rm -r /usr/local/lib/ruby/

123Next