Documente Academic
Documente Profesional
Documente Cultură
Desenvolvimento de um software
para jogadores de loterias
Florianpolis SC
2007
Euclides Pinheiro de Melo
Desenvolvimento de um software
para jogadores de loterias
Florianpolis SC
2007
Monografia de graduao sob o ttulo Desenvolvimento de um software para jogadores
de loteria, defendida por Euclides Pinheiro de Melo e aprovada em 15 de junho de 2007, em
Florianpolis, Santa Catarina, pela banca examinadora constituda pelos professores:
______________________________________________
Prof. PhD. Dalton Francisco de Andrade
Orientador
Universidade Federal de Santa Catarina
______________________________________________
Prof. Dr. Paulo Sergio da Silva Borges
Universidade Federal de Santa Catarina
______________________________________________
Prof. Dr. Ricardo Pereira e Silva
Universidade Federal de Santa Catarina
In lottery, you only have to win once.
Autor desconhecido
Sumrio
1 Introduo..............................................................................................................
.....................9
1.1 Objetivos.......................................................................................................... .................10
1.2 Objetivos especficos........................................................................................ ................10
1.3 Justificativa................................................................................................. ......................10
1.4 Limitaes........................................................................................................... ..............11
1.5 Organizao do trabalho.............................................................................. .....................11
2 Loterias........................................................................................................
.............................12
2.1 Histrico............................................................................................................................12
2.2 Loterias no Brasil..................................................................................................... .........12
2.3 Probabilidades............................................................................................................ .......14
2.4 A mente do jogador: indo contra as probabilidades.........................................................15
2.4.1 Prospect Theory................................................................................................. ....15
2.4.2 Intuio e sistemas para loterias................................................................................17
3 Sistemas para jogadores de loterias.................................................................................. .........18
3.1 Propsito............................................................................................................................18
3.2 Caractersticas gerais................................................................................. ........................19
3.3 Benefcios...........................................................................................................................20
3.4 Limitaes................................................................................................................ ..........20
4 Anlise de requisitos do software................................................................................. .............22
4.1 Glossrio dos requisitos.......................................................................................... ...........22
4.2 Requisitos em alto nvel................................................................................................... ..23
4.3 Requisitos funcionais............................................................................................... ..........24
4.4 Requisitos no funcionais.................................................................................... ..............25
5 Projeto do software..................................................................................................... ...............27
5.1 Arquitetura geral......................................................................................... .......................27
5.2 Diagrama de casos de uso........................................................................................... .......28
5.3 Solues utilizadas em todos os mdulos.........................................................................28
5.3.1 Princpio aberto-fechado (Open-closed principle)....................................................28
5.3.2 Arquitetura plugin..................................................................................... .................29
5.4 Mdulo ncleo............................................................................................... ....................29
5.5 Mdulo anlise............................................................................................................ .......31
5.6 Mdulo filtro.......................................................................................................... ............32
5.7 Mdulo gerador.............................................................................................................. ....32
5.8 Mdulo conferncia.......................................................................................... .................33
5.9 Mdulo impresso............................................................................................................ ..33
6 Implementao.................................................................................................................. .........35
6.1 Tecnologias utilizadas............................................................................................. ...........35
6.1.1 Linguagem de programao......................................................................................35
6.1.2 Ferramentas de desenvolvimento..............................................................................35
6.1.3 Hospedagem do projeto......................................................................... ....................36
6.2 Principais dificuldades encontradas..................................................................................36
6.2.1 Identificao de subclasses em tempo de execuo..................................................36
6.2.2 Interface grfica.................................................................................. .......................36
7 LagarLottery 1.0................................................................................................ ........................38
7.1 Tela principal................................................................................................................... ...38
7.2 Tela mdulo anlise.................................................................................. .........................39
7.3 Tela mdulo filtro............................................................................................................... 41
7.4 Tela mdulo gerador..................................................................................... .....................43
7.5 Tela mdulo impresso................................................................................... ...................45
7.6 Tela mdulo verificador............................................................................................ .........46
7.7 Tela atualizao de resultados.............................................................. .............................48
8 Consideraes finais e trabalhos futuros....................................................................... ............50
9 Bibliografia............................................................................................................
....................51
10 Apndice A Cdigo fonte.................................................................................................... ..52
11 Apndice B - Artigo............................................................................................. ..................278
Resumo
Winning in a lottery has always been the dream of many people since the early days of
lottery drawings, which started to take place many centuries ago.
At the same time, people have always been seeking ways to improve their chances of
becoming a winner, usually trying to discover patterns that might be present in the past results,
and putting their bets on the possible results that seemed to them the most probable to occur.
However, both the statistical analysis of previous data and the choice of a combination of bets
satisfying some established criteria often implies in hard and repetitive mechanical work, which
turns out to be even worse when it becomes necessary to fill a large number of bet cards
manually. With this scenario in mind, the objective of this work is to supply a software that can
help a wagerer to formulate and lay his bets without wasting a long time with dull tasks, as
mentioned.
The first part of this work provides some general information about lotteries and lottery
systems (software); in the sequence, a specific software developed by the author is presented
and implemented, which aims at the fulfillment of the pertaining requisites regarding the
analysis and automation of bets. Finally, the complete source code of that particular software,
(Version 1.0), is offered to be freely distributed to all those interested in the subject.
Keywords: lottery, statistical analysis, enumeration methods, software.
1 Introduo
Vencer. Seja por fortuna, poder, ou simplesmente pelo gostinho de chegar l, o homem
sempre tenta planejar algum meio de conseguir seus objetivos. Ao invs de se deixar levar pelo
puro acaso, muitos tentam bolar estratgias, simular possibilidades, para tentar chegar a um
plano vencedor.
Esta caracterstica humana est presente em diversos acontecimentos da vida; a
profisso que ir exercer, uma partida de poker, a guerra, o clima, o caminho para casa, entre
muitos outros exemplos. Cada problema tem suas particularidades, grau de certeza e dificuldade
de anlise. Por exemplo: escolher o caminho de casa envolve algumas poucas variveis, como
distncia, grau de periculosidade do lugar; um problema razoavelmente simples de chegar a
uma soluo boa. Porm, existem problemas mais complicados, onde no se tem muitas
certezas: numa partida de poker (justa), voc nunca poder saber as cartas do seu adversrio.
Mesmo no sabendo-se as cartas do oponente, isto no impediu o homem, ao longo do tempo,
de tentar imaginar meios de vencer o oponente sem ter que contar apenas com a sorte.
Entre os muitos problemas difceis de resolver, um bastante popular o problema das
loterias. A grosso modo, o problema das loterias consiste em descobrir que dezenas sero
sorteadas no prximo concurso, ou que aposta, ou conjunto de apostas, ter acertado o maior
nmero de dezenas possvel no prximo concurso.
Um fato aceito que no possvel prever exatamente o prximo resultado, assim como
no h meios de saber de certeza as cartas na mo do adversrio numa partida de poker. Mas
isso no impede a mente humana de imaginar meios de chegar perto, tentando analisar as
variveis que esto presentes e imaginar planos, cenrios possveis para tentar tomar uma
deciso melhor.
neste cenrio que entra um software para jogadores de loterias. Um software para
jogadores de loterias no uma caixa mgica, onde aperta-se um boto e consegue-se as
dezenas que iro sair no prximo concurso. Tal recurso, apesar de desejvel, no possvel de
ser concebido, devido a natureza do problema. O que um bom software para loterias pode fazer,
para auxiliar o jogador, reunir as informaes disponveis e permitir que o usurio possa
visualizar elas de maneira agradvel (utilizando-se de interface grfica, dados sob a forma de
grficos), auxiliando a sua tomada de deciso para o prximo concurso. Outra caracterstica
de automatizar tarefas repetitivas, que podem ser feitas rapidamente utilizando-se um
computador, que se fossem feitas pelo homem, seriam tediosas e passveis de erros.
O tipo de loteria abordado a loteria clssica, onde o apostador escolhe suas dezenas de
um conjunto definido, e o(s) ganhador(es) (so) quem acertar todas ou parte das dezenas
sorteadas. Exemplos deste tipo de loteria: Quina, Lotofcil, Mega sena, Dupla sena, etc (da
Caixa Econmica Federal); pick-6, pick-5, pick-4 (loterias americanas), entre muitas outras.
A concepo de um software para loterias o foco deste trabalho. Ao longo do texto,
sero detalhadas as etapas de anlise e projeto do software, levando em conta os anseios dos
jogadores de loterias, o que eles desejam que seja automatizado, que espcie de anlises iro
querer, ou seja, que estratgias eles iro querer que o software os ajude para tentar resolver o
problema. Ao final, h a implementao do que foi analisado e projetado. Devido o problema
das loterias no ser exato, h inmeras maneiras de se encarar e abordar, sendo campo frtil
para novas estratgias que a mente humana vai imaginando.
9
1.1 Objetivos
1.3 Justificativa
comum as pessoas terem idias (as vezes malucas) para tentar gerar um jogo ou bolo
de loterias. Independente se a idia for boa ou ruim, muitas vezes o que estas pessoas precisam,
para pr em prtica, de um suporte para automatizar tarefas tediosas, repetitivas, ou auxlio
para realizar alguma anlise, para comprovar alguma idia que esta pessoa teve. Por isso temos
os objetivos citados acima, pois apesar de muitas vezes o usurio ter o desejo de pr em prtica
um jogo grande, um bolo para a empresa, ningum gosta de ter que preencher manualmente
vrios cartes, ou combinar cada carto manualmente. Assim como ningum gosta de ter que
contar, resultado a resultado, para saber se deu mais pares ou mpares at hoje.
Um software que cumpra os objetivos acima, ir facilitar em muito a vida dos jogadores
de loterias, facilitar os famosos boles que acontecem dentro dos rgos pblicos e empresas
privadas. Isso promove maior sinergia entre os colaboradores e acentua o esprito de equipe.
10
Outro resultado importante de tal software, que auxiliando os jogadores, ir aumentar
o volume de jogos realizados, consequentemente aumentado o volume de dinheiro apostado,
aumentando assim a arrecadao que as loterias promovem para projetos sociais. Mais
informaes podem ser vistas na referncia [CAIXA01].
As questes de multi-plataforma, multi-idioma e pgina web para divulgao vm com
o desejo de aumentar o escopo de atuao do software, considerando que diversos pases ao
redor do globo tem seus sistemas de loterias.
Utilizar software livre, e dispor o projeto sob uma licena livre vm para, novamente,
ampliar o escopo de atuao do programa, pois sob tal licena, qualquer desenvolvedor poder
reaproveitar / personalizar o programa para suas necessidades.
1.4 Limitaes
Como dito, h inmeras estratgias para se encarar o problema das loterias. Neste
documento, anlise e implementao, sero ouvidos os jogadores e consultada literatura a
respeito para se obter algumas estratgias das inmeras possveis, logo apenas algumas das
inmeras anlises sero implementadas. Mas como o sistema ser facilmente extensvel
(objetivo e requisito), no ser difcil terceiros adicionarem suas tcnicas.
O projeto do software permite extensibilidade para qualquer tipo de loteria similar
pretendida. A implementao, para validar o projeto, conceber dois tipos de loterias: Quina e
Lotofcil, da Caixa Econmica Federal.
Este trabalho est dividido da seguinte maneira: o captulo 2 descreve loterias e discute
probabilidades. O captulo 3 d uma viso geral sobre sistemas para jogadores de loterias. Os
captulos 4, 5 e 6 tratam da soluo para o problema (anlise de requisitos, projeto e
implementao, respectivamente), enquanto que o captulo 7 exibir o sistema em sua verso
1.0, meta definida para este trabalho.
Durante a fase de projeto e implementao, haver a confeco e publicao do site do
projeto, de acordo com um dos objetivos estipulados. Assim que o desenvolvimento do software
progrida, novas informaes e verses do software sero publicadas.
11
2 Loterias
2.1 Histrico
Apesar das loterias e dos sistemas de loterias terem evoludo drasticamente atravs dos
anos, seus propsitos continuam os mesmos: arrecadar dinheiro para financiar projetos do
governo. Devido s loterias arrecadarem grandes somas em dinheiro, a maior parte dos
governos do mundo (incluindo o Brasil) no permitem o setor privado explorar este mercado.
A loteria nacional administrada pela Caixa Econmica Federal, desde 1962, quando
realizou o primeiro sorteio da loteria federal. Desde ento, a oferta de jogos de loteria tem
crescendo cada vez mais.
A partir de 1980, a Caixa adotou um sistema inovador para a realizao dos sorteios:
criou o chamado caminho da sorte. Neste caminho, que percorre o Brasil, realizado o
sorteio das loterias, e o povo da cidade em que o caminho est pode assistir apurao. Alm
12
de um auditor designado, a populao pode desta maneira auditar o resultado da loteria e do
processo. A idia do caminho, segundo a instituio, a de transparncia nos sorteios, para que
os apostadores continuem confiantes na idoneidade do sistema. Enquanto um caminho fica na
cidade do sorteio, outro caminho vai viajando para a outra e se instalando, para o sorteio
seguinte. Este sistema tem se mostrado eficaz, considerando que o volume de jogos lotricos s
vem crescendo atravs dos anos.
At o presente momento, os jogos disponveis pela Caixa pertinentes a este trabalho so:
[CAIXA03]
Mega Sena
a loteria mais difcil de acertar (e consequentemente, com prmios mais altos).
Marcar: 6 de 60 nmeros.
Premia com 4, 5, 6.
sena quina quadra
Probabilidade de acerto, 1 em 50.063.860 154.518 2.332
Dupla Sena
Tm como diferencial a existncia de dois sorteios por aposta, logo o apostador tem
duas chances de ganhar por aposta.
Marcar: 6 de 50 nmeros.
Premia com 4, 5, 6.
sena quina quadra
Probabilidade de acerto, 1 em 15.890.700 60.192 1.119
Quina
Uma das mais antigas. Tem este nome por ser sorteados apenas cinco nmeros. Tem
como caracterstica a possibilidade de jogar com mais nmeros por volante, com preo
reduzido.
Marcar: 5, 6 ou 7 de 80 nmeros.
Premia com 3, 4, 5.
quina quadra terno
(5) Probabilidade de acerto, 1 em 24.040.016 64.106 866
(6) Probabilidade de acerto, 1 em 4.006.669 21.657 445
(7) Probabilidade de acerto, 1 em 1.144.762 9.409 261
Lotomania
Uma loteria recente. Tem como caracterstica a quantidade de nmeros elevada que o
apostador precisa preencher por carto.
Marcar: 50 em 100 nmeros.
13
Premia com 0, 16, 17, 18, 19, 20.
Faixas Probabilidade
20 nmeros 1/11.372.635
19 nmeros 1/352.551
18 nmeros 1/24.235
17 nmeros 1/2.776
16 nmeros 1/472
00 nmeros 1/11.372.635
Lotofcil
Com o sucesso da Lotomania, veio depois a Lotofcil. Como o nome j diz, uma
loteria que oferece maiores chances ao apostador (probabilidade de acerto maior por aposta).
Marcar: 15 em 25.
Premia com 11, 12, 13, 14, 15.
Faixas Probabilidade
11 nmeros 1/11
12 nmeros 1/59
13 nmeros 1/691
14 nmeros 1/21.791
15 nmeros 1/3.268.760
Estas referidas loterias so pertinentes a este trabalho porque so loterias onde o usurio
escolhe uma certa quantidade de nmeros de um conjunto definido, e ganha se acertar parte ou
todas as dezenas sorteadas.
A Caixa Econmica tem ainda outros tipos de loterias, que so a Loteca, Loteria
Federal, Lotogol e Loteria Instantnea, totalizando com as citadas anteriormente, 9 tipos de
jogos escolha do apostador. O preo da aposta, para todas as citadas, varia de 50 centavos a 2
reais.
2.3 Probabilidades
Como pde ser visto no tpico acima, as chances de ganho em uma loteria so muito
pequenas. Quando falamos em chance de ganhar, estamos nos referindo a probabilidade de, em
um sorteio (um evento), de aparecer a combinao escolhida dentre as possveis (os nmeros
sorteados coincidirem com os escolhidos).
Por exemplo: um jogador realiza uma aposta no jogo Lotofcil. A probabilidade da
aposta que ele realizou ser a vencedora (acertar todos os 15 nmeros) de 1 para 3.268.760. O
motivo de a chance ser ruim o fato de haver 3.268.760 combinaes diferentes de 15 nmeros
em 25 dezenas possveis. Cada jogo tem probabilidades de ganho diferentes devido a cada jogo
14
ter um nmero de dezenas a escolher diferentes dos outros, alm do conjunto possvel de
nmeros ter tamanho diferente.
Se o mesmo jogador realizasse duas apostas diferentes no mesmo concurso, sua chance,
para o jogo citado acima, seria de 2 para 3.268.760, ou 1 para 1.634.380. Isso quer dizer que,
quanto maior a quantidade de apostas diferentes realizadas no mesmo concurso, maior a
probabilidade de ganho do apostador. Observando os extremos, se o apostador pudesse jogar as
3.268.760 combinaes possveis, este teria probabilidade 1 de ganhar; se no realizasse aposta
alguma teria probabilidade 0. Apesar de desejvel ter probabilidade 1 de ganho, invivel
devido ao custo das apostas e a impossibilidade de gerar e apostar os 3.268.760 volantes de
aposta.
comum vrios apostadores se unirem para fazer um jogo maior, ou seja, cada
apostador ajuda com uma quantia em dinheiro para realizar um jogo unificado. So os famosos
boles. Imagine um cenrio onde 10 apostadores se unem para realizar uma aposta unificada
na Lotofcil. Cada apostador contribui com 10 volantes, totalizando assim 100 volantes
(diferentes). A chance deste grupo acertar o premio mximo de 1 em 32.687. Ainda bastante
difcil de se ganhar, mas uma chance melhor do que cada jogador realizar um jogo individual
de 10 volantes (chance de 1 em 326.876). As chances aumentam quanto maior a quantidade de
apostas, e o custo fica menor quando dividindo entre mais apostadores. Um grupo muito
grande de apostadores reduz bastante o custo, porm tambm o prmio ter de ser dividido entre
estes muitos. Como o prmio de um concurso de loterias ultrapassa a casa dos milhes de reais,
geralmente um melhor negcio participar de um bolo em vez de jogar sozinho.
15
a) Efeito certeza:
Quando um ganho positivo tende a 100% de certeza, geralmente preferido a outras
opes com risco, mesmo se essas ltimas puderem resultar em um prmio mais alto, dentro de
certos limites variveis.
Foi feito um estudo com uma amostra de 95 indivduos, e propostos dois problemas: no
primeiro, o indivduo pode escolher entre jogar uma loteria com 80% de chance de ganhar
$4000 (ou seja, 20% de chance de sair com nada) e a outra opo era no jogar a loteria e
ganhar $3000 (chance 100%). O segundo problema consistia em o indivduo jogar uma loteria
com 20% de chance de ganhar $4000, ou jogar outra loteria com chance de 25% de ganhar
3000.
Pela teoria da maximizao da utilidade, o indivduo deveria jogar sempre naquela em
que, proporcionalmente s probabilidades, oferece maior ganho. Porm, o efeito certeza mexe
com a cabea dos indivduos, que preferiram pegar os $3000 porque era um prmio que
ganhariam com certeza. Quando a probabilidade de ganhar $4000 era pequena e $3000 tambm,
foram no prmio mais alto (os $4000). Houve uma inverso da preferncia de jogo, devido ao
efeito certeza.
b) Efeito reflexo:
Quando as loterias envolvem perdas ao invs de ganhos, ou colocando-se sinais
negativos nos prmios, as preferncias se invertem. Isto significa dizer que a averso ao risco
que verifica-se em loterias compostas apenas de prmios positivos transforma-se em afeio ao
risco para o caso de perdas.
As hipteses de que os indivduos evitam em suas decises alternativas incertas
(preferncia por ganhos certos) ou optam pela mnima variabilidade (a varincia de (3000, 1)
zero) tambm no so confirmadas pelos resultados obtidos experimentalmente.
Na pesquisa, a loteria (- 4000, 0.80) preferida (92% das respostas) loteria (-3000, 1),
apesar de esta ltima ter um valor esperado maior e uma varincia menor.
c) Efeito isolamento:
Entre alternativas que contm componentes comuns, a escolha feita com base nas
partes que as distinguem. Esse critrio de deciso pode ocasionar preferncias inconsistentes.
Considere-se, por exemplo, uma loteria composta de dois estgios.
No primeiro estgio existe uma probabilidade de 75% de encerrar-se o jogo sem ganhos
nem perdas (L11), e uma chance de 25% de passar-se para o segundo estgio (L12), onde as
possibilidades so L21: (4000, 0.80; 0, 0.20) e L22: (3000, 1). Investigado o comportamento
decisrio de 141 indivduos nessa loteria composta, 110 pessoas (78%) optaram por L22. Este
resultado ope-se seleo modal observada no problema 2 citado na discusso do Efeito
Certeza, cujas alternativas eram idnticas s do presente problema aps combinar-se as
probabilidades dos primeiro e segundo estgios. Por qu essa discrepncia? Aparentemente, os
decisores ignoraram o primeiro estgio do jogo, fazendo suas opes como no problema 1. O
efeito isolamento implica no aumento da atratividade da certeza contingente, relativamente a
uma opo de risco com as mesmas probabilidades combinadas e ganhos.
16
esto nos extremos (perto de 100%, perto de 0%) as decises dos indivduos se tornam
contraditrias ao modelo da mxima utilidade, e algumas vezes imprevistas. Um dos exemplos
mostrou isso, o caso das loterias, onde os jogadores apostam, mesmo com nfima chance de
ganho, devido ao enorme prmio. A loteria um caso onde chance perto de 0%.
Um exemplo que envolve perda seria quando as pessoas resolvem praticar esportes
radicais. A probabilidade de acontecer uma tragdia (morte) pequena, porm a perda muito
grande (a morte, uma perda infinita). Porm, as pessoas mesmo assim praticam esportes
radicais, porque neste momento esto olhando para a probabilidade da perda que muito
pequena, e no da perda muito grande.
A prospect theory citada neste trabalho apenas como uma justificativa de porque as
pessoas jogam na loteria, no sendo usada no desenvolvimento do software.
Outro fator que afeta a mente das pessoas ao tomar suas decises de jogar ou no numa
loteria, so as crenas em determinados sistemas para loterias, ou crenas em fatores msticos,
onde o individuo acredita que a probabilidade de ganho aumentou, quando na realidade,
matematicamente, a mesma.
Imaginemos um caso, em que um jogador em particular, sonhou com um conjunto de
dezenas especficas. Este jogador em particular costuma jogar num jogo com 6 dezenas, e
coincidentemente sonhou com 6 nmeros. Este jogador vai se sentir com sorte, vai achar que
suas chances de ganho aumentaram drasticamente, porque afinal, sonhou com 6 nmeros! Sua
deciso de jogar ou no teve uma influncia em crenas, e no apenas na probabilidade.
Um exemplo que envolve sistemas para jogadores de loterias so as anlises realizadas
em resultados passados. Quando um jogador observa que, por exemplo, esto sendo sorteadas
muitas dezenas altas, ele acredita que se jogar em dezenas altas, ir aumentar sua probabilidade
de ganho, quando novamente, a probabilidade de o jogador ganhar com um carto
(independente de dezenas altas ou baixas) a mesma (j que sorteios de loterias no so
afetados por resultados passados, j que os sorteios no tem memria). Um efeito similar o
jogador acreditar que deveria jogar mais em dezenas baixas, porque esto atrasadas.
Estes fatores pesam nas decises de jogo dos apostadores, e estes gostam de usar estes
sistemas porque faz eles sentirem mais confiantes. devido a mais este fator, que explica o
motivo das pessoas jogarem em loterias, apesar da probabilidade ser muito pequena de ganhar.
17
3 Sistemas para jogadores de loterias
3.1 Propsito
Um software para jogadores de loterias tem como propsito principal aliviar o usurio
de tarefas que no demandam inteligncia, ou seja, tarefas mecnicas e repetitivas; e no apenas
aliviar o usurio, como tambm dar celeridade e convenincia ao processo de se jogar na
loteria.
O processo de jogar na loteria, consiste, basicamente, nos seguintes passos
representados na figura abaixo:
1. Analisar: consiste do passo do usurio pensar, pesquisar, coletar dados para realizar
alguma anlise em resultados passados ou outra fonte que julgue adequada para escolher
dezenas a jogar ou gerar um bolo. Este passo opcional.
2. Gerar: consiste em o usurio inventar um meio de combinar suas dezenas, gerando
18
tipicamente um bolo. Este passo opcional.
3. Filtrar: restringir, usando alguma regra, os jogos gerados, a fim de reduzir os custos do
jogo, ou fazer caber a quantidade de cartes na verba disponvel. Este passo opcional.
4. Marcar volantes: consiste no preenchimento fsico dos volantes de loteria, a fim de se
poder realizar a aposta em uma casa lotrica credenciada. Passo requerido.
5. Jogar: consiste no ato de submeter os volantes ao agente lotrico e realizar o pagamento.
Passo requerido.
6. Conferir: averiguar se houve sucesso ou fracasso no jogo que apostou. Passo requerido.
Observando-se cada passo descrito, nota-se que existe uma srie de atividades manuais
que o usurio precisaria executar se no usar um software para jogador de loterias. Vamos a
algumas:
No caso da anlise, em particular de resultados passados, teria que manualmente colher
todos os resultados de loteria, e aplicar meios de visualizar estes dados de forma mais
agradvel. Ex: visualizar a distribuio de pares e mpares nos resultados passados:
colher cada resultado, contar em cada resultado quantos pares e mpares deram, montar
uma tabela ou grfico exibindo o resultado da anlise. Manualmente, mais de um dia
de trabalho;
No caso de gerar, em particular em boles, onde se costumam jogar, por exemplo,
centenas ou milhares de volantes. Enumerar todos os nmeros de cada volante um
trabalho extremamente repetitivo e demorado;
No caso de filtrar, aplicar regras de rejeite ou aceite em cada volante, novamente um
trabalho demorado;
No caso de marcar volantes, pintar cada clula de cada volante de loteria usando caneta
algo que pode de dias a semanas, dependendo do tamanho do jogo;
No caso de conferir, examinar cada carto para determinar a quantidade de erros e
acertos, no caso de haver muitos volantes, demanda muito tempo e esforo;
19
Realizar anlises sobre os resultados passados;
Gerar boles;
Filtrar boles gerados;
Imprimir os jogos em volantes de loteria;
Conferir os jogos.
O que motiva os softwares para este ramo, terem estas caractersticas, descrito na
seo 3.1 acima, pois estas caractersticas cobrem o grande trabalho braal de se jogar na
loteria.
Tais caractersticas puderam ser encontradas na referncia [GAIL01] e tambm nos
seguintes softwares para jogadores de loteria existentes (maiores detalhes sobre eles, acesse o
site):
SpLoto ( http://www.spolti.com.br/sploto/ );
Gerasorte ( http://www.gerasorte.com.br/ );
Papasorte ( http://www.loteria.com.br/ );
Sorte certa ( http://www.sortecerta.com.br/ );
HtLoto ( http://www.hypertech.com.br/ );
3.3 Benefcios
3.4 Limitaes
comum, quando as pessoas ouvem sobre softwares de loteria, pensar que inventou-
se um jeito garantido de ganhar, ou ento pensar que o software vai ganhar para mim. Como
j discutido ao longo do trabalho, o software uma ferramenta que voc usa para facilitar a vida
ao jogar na loteria, e depende da estratgia, de entrada do usurio para fornecer sada.
Ao acessar sites de produtos comerciais de loteria, comum anunciarem que o software
vai te fazer ganhar, mas esteja ciente que todo software deste tipo sofre desta limitao, que a
impossibilidade de garantir ganhos (claro, possvel garantir ganho se especificar alguns
cenrios, mas pense de modo geral).
20
Outra limitao est no fato de que o software nunca vai satisfazer todos os desejos de
todos os jogadores: cada jogador tem sua estratgia nica e particular que acha adequado para
vencer na loteria. Os softwares disponveis renem algumas estratgias comuns que boa parte
dos jogadores gostam / costumam jogar e disponibilizam no software. No captulo 5, projeto do
software, ser descrito as decises de projeto que tentam contornar esta limitao encontrada
em praticamente todos os softwares de loteria existentes: falta de extensibilidade.
21
4 Anlise de requisitos do software
22
considerada baixa se for menor ou igual que a dezena central. A dezena central obtida
dividindo-se a maior dezena por 2. Em caso de o resultado no ser uma dezena
pertencente ao conjunto dos naturais, despreza-se as casas decimais.
filtro colunas tipo de filtro especfico, destinado a eliminar volantes que contenham
uma determinada quantidade de dezenas em cada coluna.
filtro dezena filtro destinado a eliminar volantes que contenham determinadas dezenas
especficas.
filtro linhas filtro destinado a eliminar volantes que contenham determinada
quantidade de dezenas por linha.
filtro par x mpar filtro destinado a eliminar volantes que contenham determinada
quantidade de dezenas pares e determinada quantidade de dezenas mpares.
forma de grfico um tipo de visualizao de anlise. Consiste em resumir os dados da
anlise, exibindo por exemplo, sob a forma de um grfico de pizza, ou um grfico de
barras.
forma de tabela um tipo de visualizao de anlise. Consiste em exibir, de forma
detalhada, a anlise sobre cada resultado, usando uma estrutura tabular.
gerador um algoritmo especfico destinado a gerar um conjunto de volantes de loteria.
jogo gerado um conjunto de volantes gerados.
plugin forma de extender um programa original, sem que haja necessidade de
modificar o cdigo ou recompilar o programa original. Consulte
http://en.wikipedia.org/wiki/Plugin para maiores detalhes.
URL formato de endereo eletrnico. Consulte http://www.faqs.org/rfcs/rfc1738.html
para maiores detalhes.
verificador algoritmo destinado a contar quantos acertos houve sobre cada volante de
um jogo gerado. necessrio o fornecimento do resultado de loteria como entrada.
volante uma combinao de nmeros possvel de ser jogada em um determinado tipo
de loteria.
web entende-se por web, no contexto deste trabalho, como um servidor que
disponibiliza um arquivo usando o protocolo HTTP, acessvel atravs da internet.
23
4. Permitir restries sobre jogos combinados (conhecidos tipicamente como filtros).
5. Realizar conferncia dos jogos gerados.
6. Imprimir os jogos gerados em volantes de loterias.
7. Software dever ser extensvel para outras loterias similares.
8. Software dever ser fcil de adicionar novas funcionalidades.
9. Software dever rodar pelo menos em Linux e Windows.
10. Verses em portugus do Brasil e ingls americano, no sendo difcil adaptar para outros
idiomas.
11. Pgina web para divulgao do software / projeto.
Nem todos os requisitos indicam algo que o sistema deve fazer, e esto presentes na
listagem acima. So os chamados requisitos no funcionais. Tanto os funcionais e no
funcionais sero detalhados nos tpicos abaixo. Termos em itlico na seo 4.2 e 4.3 sero
explicados na seo 4.4, glossrio dos requisitos.
Para cada requisito alto nvel funcional, ser detalhado abaixo, na seqncia O nmero
corresponde ao requisito alto nvel. So eles:
1. Carga de resultados - O sistema deve, na ausncia de uma base de resultados,
perguntar ao usurio se deseja realizar o download dos resultados via web. O sistema
deve permitir, quando for do desejo do usurio, fazer o download dos resultados, e
tambm quando for de desejo do usurio, exibir os resultados carregados. Para tal, ser
fornecida uma URL para download da base.
2. Anlises - Realizar anlises sobre a base de resultados. Para a verso 1.0 do sistema,
devero ser implementadas cinco anlises: anlise par x mpar, anlise altas x baixas,
anlise linhas, anlise colunas e anlise freqncia das dezenas. Estas anlises sero
detalhadas por forma de tabela e por forma de grfico.
3. Geradores - O sistema deve, a partir das dezenas do usurio, ou ento todas as dezenas
possveis, enumerar volante a volante, cada possvel combinao que formada a partir
das dezenas escolhidas. Algoritmo na referncia [MICHAEL01].
4. Filtros - O sistema deve, a partir de um jogo gerado, permitir que o usurio especifique
regras para eliminar ou manter volantes com determinadas caractersticas. Para a verso
1.0 do sistema, dever ser implementado cinco filtros: filtro par x mpar, filtro altas x
baixas, filtro linhas, filtro colunas e filtro dezena. Note que neste caso, os filtros esto
casando com as anlises que devero ser implementadas, mas no necessariamente uma
anlise precisar ter um filtro equivalente, apesar de ser comum (uma vez que
determinada anlise pode gerar o desejo de manter ou retirar cartes com determinada
caracterstica observada na anlise).
5. Verificadores - O sistema deve, para um jogo gerado qualquer, permitir que o usurio
24
entre com um resultado, e ento o sistema exibe um relatrio mostrando os acertos de
cada volante que pertence ao jogo gerado. Ao final do relatrio, o sistema exibe um
sumrio dizendo quantos cartes fizeram tantos pontos, como mostra o modelo a seguir:
0.001 : 05 acertos
0.002 : 04 acertos
n : xx acertos
= Resumo =
0 acertos = x cartes (soma dos cartes que fizeram 0 acertos)
1 acertos = y cartes (soma dos cartes que fizeram 1 acertos)
n acertos = z cartes (soma dos cartes que fizeram n acertos)
6. Imprimir - O sistema deve, para um jogo gerado qualquer, permitir que o usurio
imprima cada volante diretamente sobre o papel utilizado nas lotricas. Para a verso
1.0, suportado volantes da Caixa Econmica para Quina e Lotofcil, porm o formato
do carto poder ser alterado via configurao. Sero suportadas impressoras que
permitem puxar o papel do tamanho do volante, e no centro da rea de impresso.
Para cada requisito alto nvel no funcional, ser detalhado abaixo, na seqncia. O
nmero corresponde ao requisito alto nvel. So eles:
7. Suporte a diversas loterias - Sistema dever, atravs de configurao, aceitar tipos
diferentes de loteria. Para a verso 1.0, para demonstrar essa caracterstica, o sistema
dever suportar dois tipos de loterias diferentes: Quina e Lotofcil. As peculiaridades de
cada tipo de jogo dever estar abstrada atravs de configurao, no podendo ser usadas
regras especficas de alguma delas codificada no ncleo do sistema, o que afetaria
negativamente este requisito de ser flexvel.
8. Extensibilidade - Entendendo por novas funcionalidades: adio de novos(as)
anlises, filtros, tipos de loterias, geradores e verificadores. O sistema dever se
comportar, para estas novas funcionalidades, como se comporta um sistema baseado em
plugins: na presena de um novo artefato, deixar este novo artefato disponvel para uso,
sem necessidade de configurao extra ou modificao de cdigo.
9. Plataforma - Sistema dever rodar, no mnimo, em Windows 98 SE, Windows 2000,
Windows XP e Linux (distribuio Debian Sarge).
10. Internacionalizao - Externalizar o texto traduzvel em arquivos para posterior
traduo, no necessitando recompilar cdigo para se ter o sistema em outro idioma. O
idioma padro ser o ingls americano, sendo que dever haver uma traduo para
portugus do Brasil. A deteco do idioma se dar atravs da configurao de idioma do
ambiente do usurio.
25
11. Distribuio - Disponibilizar o projeto em um repositrio de projetos de cdigo
aberto, estando l disponvel no controle de verso do repositrio tanto os fontes quanto
o trabalho de concluso de curso. No caso, o repositrio ser o SourceForge
(http://sourceforge.net/).
26
5 Projeto do software
Com base nos requisitos descritos no captulo anterior, este captulo contm o projeto do
software que cumpre os requisitos citados. Neste captulo so mostrados detalhes da arquitetura
adotada, diagramas de classes e outros artefatos de projeto de software.
27
5.2 Diagrama de casos de uso
O princpio aberto-fechado diz que classes devem ser abertas para extenso, porm
fechadas para modificao [FREEMAN01].
Este princpio vem de referncias sobre padres de projeto de software, e utilizado em
vrios mdulos para suportar a extensibilidade de funcionalidades. Por exemplo, para adicionar
uma nova anlise disponvel, o programador no precisa alterar uma nica linha de cdigo
sequer do sistema inteiro, basta criar uma nova subclasse de uma abstrao de anlise j
existente, ou seja, extender de algo que j existe, j foi bem testado e funciona. Mais
informaes podem ser obtidas na referncia da citao acima.
28
5.3.2 Arquitetura plugin
O sistema usa, em vrios mdulos, a noo de uma arquitetura plugin, no sentido que
cdigo novo introduzido no requer mudana em cdigo existente para que o cdigo existente
perceba e possa fazer uso das novas funcionalidades adicionadas. Alguns exemplos clssicos,
para facilitar o entendimento:
Navegadores de internet suportam plugins para adicionar novos tratadores de tipo de
mdia: por exemplo, o usurio instala o plugin do Macromedia Flash para suportar este
tipo de mdia no navegador, e o cdigo do navegador no alterado ou recompilado;
Editores de imagem, como o Photoshop, Gimp, Corel suportam plugins para aplicar
efeitos nas imagens em edio;
Ambientes de desenvolvimento, como o Eclipse e o Netbeans, permitem que novas
funcionalidades sejam agregadas ao ambiente. O Eclipse levou o conceito to longe que
o prprio software apenas um grande gerenciador de plugins, no fornecendo ele
prprio funcionalidade de uso.
No caso deste software de loterias, foi utilizado este conceito para que outros
programadores possam adicionar novas anlises, filtros, tipos de jogos, verificadores e
geradores sem precisar tocar em uma nica linha de cdigo sequer de todo o sistema. Isso
facilita muito a adio destas novas funcionalidades, pois quem assim o quiser fazer, apenas
precisa escrever seu novo cdigo de interesse, sem se preocupar em como tornar isso disponvel
para a estrutura existente. A estrutura existente capaz de detectar que algo novo est presente e
tratar de encaix-la no contexto. Deste modo, o requisito de extensibilidade facilitada fica
garantido.
Ficar evidenciado, em cada seo a seguir, as abstraes que suportam essa arquitetura
plugin. No captulo de implementao (captulo 6), ser mostrado como foi implementada a
capacidade do sistema reconhecer cdigo novo sem necessidade de alterao de cdigo
existente ou recompilao.
Este mdulo contm classes e abstraes comuns teis para os outros mdulos. O
diagrama de classes, com as classes mais importantes:
29
Figura 5.4.1: Diagrama de classes do mdulo ncleo
30
GameManager, na inicializao, obtm todos os jogos configurados. Aps este passo,
GameManager ter uma coleo de GameConfiguration disponveis. H a escolha de um
GameConfiguration para uso corrente no sistema, e este disponibilizado aos outros mdulos.
Mais detalhes sobre estes passos, consultar o captulo de implementao (captulo 6).
O mdulo anlise define, para o sistema, uma abstrao mnima do que seria uma
anlise de loteria, e vai especializando esta abstrao para promover facilidades ao
desenvolvedor. Quanto mais prximo da folha, da hierarquia de especializao, mais fcil a
implementao desta anlise, pois mais cdigo j est pronto e disponvel para o
implementador, porm mais restrito este fica quanto a natureza de sua anlise. O contrrio
tambm verdadeiro: quanto mais prximo da raiz a classe estiver, mais genrica ela , fornece
mais liberdade, ao custo de que menos funcionalidades prontas j estaro disponveis, exigindo
mais esforo do implementador. Vamos a figura para tornar mais claro a idia:
31
5.6 Mdulo filtro
Muito similar estrutura do mdulo anlise, o mdulo filtro prov uma abstrao bsica
do que um filtro, e especializa para facilitar a quem for implementar um novo filtro com
algum cdigo comum. No topo da hierarquia do mdulo temos a Interface Filterable, que
basicamente define um mtodo para aceitar ou rejeitar um GameCard. Desta forma, vrios
filtros podem ser implementados, onde cada regra especfica do filtro uma classe que
implementa esta interface, sobrescrevendo este mtodo que aceita ou rejeita um carto,
especificando a regra especfica no corpo do mtodo. Uma classe Manager responsvel pela
carga e disponibilizao dos filtros para o sistema. O diagrama de classes, na figura abaixo:
Define o que necessrio para obter como sada um jogo gerado. Tambm encontrado
neste mdulo a abstrao do que o jogo gerado, bem como facilidades para ler e escrever um
arquivo de jogo gerado.
Pode parecer mistura de implementao e projeto quando se fala de um arquivo de jogo
gerado, uma vez que est se especificando a persistncia em arquivo, mas de todo modo, se faz
necessrio levar isso em conta no projeto, uma vez que um jogo gerado pode conter milhes de
volantes de loteria, logo se faz necessrio definir adequadamente este arquivo de antemo para
tentar otimizar o uso de espao e projetar abstraes para tornar agradvel a leitura e escrita
deste arquivo. As classes principais esto na figura abaixo:
32
Figura 5.7.1: Classes do mdulo gerador
Conferir um jogo gerado levou a uma simples Interface, devido a baixa complexidade de
especificar uma abstrao para este problema em particular. A classe concreta SimpleVerificator
o verificador padro do sistema, que segundo os requisitos, deve gerar um relatrio simples de
averiguao.
33
Devido o fato de a impresso de um jogo gerado estar intimamente ligado a um tipo de
loteria (uma vez que cada tipo de jogo utiliza um layout fsico de carto de loteria diferente),
imaginou-se a necessidade de cada tipo de jogo ter uma classe responsvel pela impresso deste
tipo de jogo. Mas pensando em facilitar a vida do desenvolvedor e evitar repetio de cdigo,
criou-se uma hierarquia no estilo do mdulo anlise, onde h uma especificao alto nvel do
que necessrio para imprimir e criou-se especializaes para cada tipo de jogo de loteria, onde
as especializaes precisam implementar e escrever menos cdigo novo (aproveitar cdigo
comum da superclasse). Vamos ao diagrama para facilitar o entendimento:
34
6 Implementao
Como este trabalho de cdigo aberto, a escolha das tecnologias tem de levar este
aspecto em conta, uma vez que se h o desejo da sociedade em poder acessar e editar este
cdigo, h a preferncia que este o seja feito usando tecnologias livres, ou no mnimo gratuitas,
para que, quem for manusear o fonte, possa instalar as mesmas ferramentas que o
desenvolvedor principal utilizou. Seria ruim, imaginando que eu fosse um desenvolvedor novo,
querendo conhecer e editar o cdigo do projeto, tivesse que comprar uma ferramenta cara para
poder abrir a estrutura de projeto de cdigo e editar os fontes.
35
6.1.3 Hospedagem do projeto
36
toda a interface do usurio. Isso ficar mais claro no captulo 7, que mostra o software na verso
1.0.
tambm por este motivo que as classes que determinam a abstrao do mdulo tem
mtodos para obter nome ou obter descricao, pois a interface grfica no conhece de
antemo as funcionalidades que est fornecendo. A interface obtm, em tempo de execuo, as
informaes para mostrar ao usurio. Isso deixou o sistema extremamente flexvel e fcil de
adicionar novas habilidades.
37
7 LagarLottery 1.0
LagarLottery foi o nome dado ao software, por este motivo este captulo tem este nome.
Por se tratar de um cdigo que est disponvel em um repositrio americano (SourceForge) e
estar disponvel para o mundo, escolheu-se um nome em ingls para o produto (e por este
mesmo motivo que o cdigo fonte est em ingls).
Este captulo visa mostrar algumas telas do programa em sua verso 1.0, demonstrando
as funcionalidades disponveis. um captulo mais visual (imagens) do que textual.
Primeira tela do sistema. questionado ao usurio que tipo de loteria este gostaria de
trabalhar. Note que a lista de loterias disponveis populada dinamicamente de acordo com os
arquivos de configurao de loteria disponveis. Perceba tambm a barra lateral com botes:
para cada mdulo do sistema, criou-se um boto que aciona a tela que gerencia o mdulo em
questo. No menu superior esquerdo, h a opo de atualizar a base de resultados ou listar os
resultados da base atual.
38
7.2 Tela mdulo anlise
Na figura abaixo, temos a execuo da anlise Par x mpar. aberto a anlise em uma
nova janela, para que o usurio possa executar vrias simultaneamente. A figura 7.2.2 mostra a
viso da tabela, onde para cada resultado (primeira coluna) temos a categoria que este resultado
se encaixa (marcado com um X verde). As demais colunas mostram as categorias possveis,
sendo o prmeiro nmero antes do hfen o nmero de pares, logo o outro nmero aps o hfen
o nmero de mpares). A figura 7.2.3 resume a tabela em um grfico de pizza.
39
Figura 7.2.2: Anlise par x mpar - viso da tabela
40
Figura 7.2.3: Anlise par x mpar - viso do grfico
A tela mdulo filtro tambm possui o recurso de obter filtros em tempo de execuo, e
apresentar uma lista para o usurio adicionar os filtros. Vrios filtros podem ser encadeados um
sobre o outro. possvel mover a posio dos filtros ou remover da lista. Veja nas figuras
abaixo:
41
Figura 7.3.1: Tela mdulo filtro
42
Figura 7.3.2: permitido empilhar quantos filtros quiser
43
Figura 7.4.1: Tela inicial do mdulo gerador - lista de geradores disponveis
44
Figura 7.4.2: Tela de uso do gerador de todas as combinaes possveis
O mdulo impresso possui uma interface bastante simples, uma vez que uma
implementao de classe responsvel por imprimir um tipo de jogo especfico j est
especificada no arquivo de configurao; logo basta apenas o usurio informar que jogo gerado
quer imprimir, que o sistema toma o trabalho de instanciar a classe concreta responsvel por
imprimir aquele tipo de jogo. Ver figura abaixo:
45
Figura 7.5.1: Tela do mdulo de impresso
46
Figura 7.6.1: Tela inicial do mdulo verificador
47
Figura 7.6.2: Resultado do verificador simples
Por fim, temos a tela de atualizao da base de resultados. Ela exibe ao usurio o ltimo
carto da base, e exibe a URL padro que estava configurada no arquivo de configurao,
podendo o usurio alterar neste momento. Se decidir por atualizar a base, o sistema conectar
ao site especificado, ir fazer o download do arquivo apontado e construir a nova base de
resultados. Ver figura abaixo para a tela.
48
Figura 7.7.1: Tela atualizao da base de resultados
49
8 Consideraes finais e trabalhos futuros
Com este trabalho, ao longo dos captulos, mostrei que um software para jogadores de
loteria uma ferramenta til, e que uma ferramenta desta natureza pode ser muito interessante,
at para quem no costuma jogar muito na loto.
Um grande desafio deste trabalho foi tentar contornar o problema da extensibilidade:
cada jogador tem sua idia nica e particular de gerar um jogo, realizar uma anlise, filtrar
cartes, em fim, cada jogador de loteria tem a sua grande idia, e no possvel prever isso de
antemo. A soluo adotada neste trabalho foi deixar o software com vrios pontos de
extensibilidade (um em cada mdulo) para que o jogador pudesse ele mesmo (se tiver
conhecimento de programao) ou pedir para que outro o faa (o cdigo livre) para adicionar
a sua to particular funcionalidade. Se o software no tivesse sido projetado para ter os pontos
de extensibilidade e usar a arquitetura plugin, essa tarefa de adicionar cdigo novo seria
muito mais demorada e penosa. Mas com essa soluo, uma nova anlise ou filtro pode ser
adicionado em questo de minutos.
Neste ponto temos uma possibilidade de trabalho futuro (verso 2.0) do software:
permitir a insero de cdigo novo (anlise, filtro, etc) atravs de uma linguagem de script, no
estilo que ferramentas de escritrio como o Microsoft Excel permite adicionar atravs de
macros: o usurio poder, atravs de uma linguagem simples, especificar uma nova
funcionalidade e executar esta nova funcionalidade no prprio ambiente.
Outra possibilidade de trabalho futuro est em capturar regras de anlise do usurio,
para que o software possa, atravs destas regras fornecidas, processar os dados da anlise
automaticamente. Por exemplo: imagine que voc sempre olha a caracterstica X da anlise de
pares x mpares, procurando sempre por um padro Y. Se voc pudesse dizer isso para o
software, este poderia colorir a tabela resultante com cores diferentes indicando um padro
fornecido.
Durante o desenvolvimento deste trabalho, colocou-se em prtica muito contedo
aprendido durante as disciplinas. Em especial, usou-se muito engenharia de software para criar
o projeto deste trabalho: tentou-se aplicar boas prticas de desenvolvimento orientado a objeto,
com forte influncia do livro da referncia [FREEMAN01], o qual indico com grande
positividade.
Por fim, deixo o convite a realizar o download do projeto em http://sourceforge.net/
projects/lagar-lottery/ , experimentar o software e contribuir com suas idias e cdigo para que
este seja um dos melhores entre os softwares para jogadores de loterias existentes.
50
9 Bibliografia
[CAIXA01] Repasses sociais das loterias. Disponvel em:
<http://www.caixa.gov.br/Loterias/Repasses_Sociais/>. Acesso em: abril de 2006.
[NASPL] North American Association of State and Provincial Lotteries. Disponvel em:
http://www.naspl.org/history.html. Acesso em: junho de 2006.
[CAIXA03] Tipos de jogos de loteria. Disponvel em:
http://www.caixa.gov.br/loterias/index.asp. Acesso em: junho de 2006.
[PAULO 01] BORGES, Paulo Sergio da Silva, Dr. Probabilidade, Inferncia e Deciso.
Universidade Federal de Santa Catarina. Tese titular. Ano: 1998. Captulo 4
[GAIL01] HOWARD, Gail. Lottery master guide. 2003. Smart luck publishers
[MICHAEL01] Combination Generator. Disponvel em:
http://www.merriampark.com/comb.htm. Acesso em: abril de 2006.
[FREEMAN01] Eric Freeman e outros. Head First Design Patterns. 2004. Oreilly
[SUN01] Linguagem java. Disponvel em: http://java.sun.com. Acesso em: abril de 2006.
[STROUSTRUP01] The C++ programming language. Disponvel em:
http://www.research.att.com/~bs/C++.html. Acesso em: abril de .
[ECLIPSE01] Eclipse IDE. Disponvel em: http://www.eclipse.org. Acesso em: abril de 2006.
[NETBEANS01] Netbeans IDE.Disponvel em: . Acesso em: abril de 2006.
[SOURCEFORGE01] SourceForge. Disponvel em: http://sourceforge.net/. Acesso em: abril de
2006.
[JAVAWORLD01] Identify subclasses at runtime. Disponvel em:
www.javaworld.com/javatips/jw-javatip113_p.html. Acesso em: abril de 2006.
- No Referenciada:
JONES, Prof. Winning Lotto/Lottery for everyday players. Estados Unidos: Cardoza
publishing, 2002.
Wheels / Covering Designs. Disponvel em: <http://thelotteryinstitute.tripod.com/wheels.htm>.
Acesso em: fevereiro de 2006.
La Jolla Covering Repository. Disponvel em: <http://www.ccrwest.org/cover.html>. Acesso
em: fevereiro de 2006.
GNU GPL, licena de software. Disponvel em: <http://www.gnu.org/copyleft/gpl.html>.
Acesso em: maro de 2006.
51
10 Apndice A Cdigo fonte
52
/*
*AboutDialog.java
*
*Createdon16deMaiode2007,22:18
*/
packagebr.ufsc.inf.lagar.main;
importjava.awt.Color;
/**
*
*@authorlagar
*/
publicclassAboutDialogextendsjavax.swing.JDialog{
/**CreatesnewformAboutDialog*/
publicAboutDialog(java.awt.Frameparent,booleanmodal){
super(parent,modal);
initComponents();
this.setLocationRelativeTo(null);
this.setBackground(Color.WHITE);
this.pngLabel.setBackground(Color.WHITE);
this.pngLabel.setForeground(Color.WHITE);
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
pngLabel=newjavax.swing.JLabel();
jSeparator1=newjavax.swing.JSeparator();
jPanel1=newjavax.swing.JPanel();
jLabel1=newjavax.swing.JLabel();
jLabel2=newjavax.swing.JLabel();
jLabel3=newjavax.swing.JLabel();
jButton1=newjavax.swing.JButton();
jLabel4=newjavax.swing.JLabel();
jLabel5=newjavax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
setBackground(java.awt.Color.white);
setResizable(false);
pngLabel.setBackground(newjava.awt.Color(255,255,255));
pngLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
pngLabel.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/LagarLottery1.png")));
pngLabel.setToolTipText("imagemporAmaweks");
jLabel1.setFont(newjava.awt.Font("Dialog",1,18));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("LagarLottery1.0");
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("EuclidesPinheirodeMelo");
53
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("lagar_lottery@yahoo.com.br");
org.jdesktop.layout.GroupLayoutjPanel1Layout=new
org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayou
t.LEADING)
.add(jLabel2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,264,
Short.MAX_VALUE)
.add(jLabel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,264,
Short.MAX_VALUE)
.add(jLabel3,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,264,
Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,34,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel3)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
jButton1.setText("Terms");
jButton1.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jSeparator1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,288,
Short.MAX_VALUE)
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,pngLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,288,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(jLabel4,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,96,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jButton1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel5,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,96,
Short.MAX_VALUE))
);
54
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(pngLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,179,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jSeparator1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,10,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.B
ASELINE)
.add(jButton1)
.add(jLabel4,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
24,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jLabel5,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,24,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap(12,Short.MAX_VALUE))
);
layout.linkSize(newjava.awt.Component[]{jLabel4,jLabel5},
org.jdesktop.layout.GroupLayout.VERTICAL);
pack();
}//</editorfold>//GENEND:initComponents
privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_jButton1ActionPerformed
newTermsDialog(null,false).setVisible(true);
}//GENLAST:event_jButton1ActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JButtonjButton1;
privatejavax.swing.JLabeljLabel1;
privatejavax.swing.JLabeljLabel2;
privatejavax.swing.JLabeljLabel3;
privatejavax.swing.JLabeljLabel4;
privatejavax.swing.JLabeljLabel5;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JSeparatorjSeparator1;
privatejavax.swing.JLabelpngLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*AbstractGameFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
55
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter;
importbr.ufsc.inf.lagar.main.GameCard;
publicabstractclassAbstractGameFilterimplementsFilterable{
privatebooleanmode;
privateStringinput;
/**
*CreatesanewinstanceofAbstractGameFilter
*/
publicAbstractGameFilter(){
}
publicvoidsetAcceptReject(booleanmode){
this.mode=mode;
}
publicvoidsetTextInput(Stringinput)throwsTextInputFilterException{
this.validateInput(input);
this.input=input;
}
publicabstractvoidvalidateInput(Stringinput)throws
TextInputFilterException;
publicbooleanisMode(){
returnmode;
}
publicStringgetInput(){
returninput;
}
publicbooleanacceptGame(StringgameName){
returntrue;
}
publicStringtoString(){
returnthis.getFullName();
}
}
/*
*AllColumnFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
56
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
importbr.ufsc.inf.lagar.filter.Filterable;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.util.Arrays;
publicclassAllColumnFilterextendsAbstractGameFilter{
privateint[]inputBalls;
privateintlineSize;
privateint[]catsCount;
privateint[][]colsData;
privateintnumCols;
/**
*CreatesanewinstanceofAllColumnFilter
*/
publicAllColumnFilter(){
this.lineSize=GameManager.getCurrentGame().getNumbersPerLine();
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
String[]params=input.split(Filterable.OR_SEPARATOR);
this.inputBalls=newint[params.length];
for(inti=0;i<params.length;++i){
Strings=params[i];
try{
this.inputBalls[i]=Integer.parseInt(s.trim());
}
catch(NumberFormatExceptionnfex){
thrownewTextInputFilterException(nfex);
}
Arrays.sort(this.inputBalls);
this.catsCount=newint[this.lineSize+1];
this.numCols=GameManager.getCurrentGame().getNumbersPerCard()/
this.lineSize;
for(inti=1;i<=this.lineSize;++i){
57
this.colsData=newint[this.lineSize+1][numCols];
}
for(inti=1;i<=this.lineSize;++i){
intcurrNum=i;
for(intj=0;j<numCols;++j){
this.colsData[i][j]=currNum;
currNum+=this.lineSize;
}
publicStringgetShortName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_column_filter");
}
publicStringgetFullName(){
returngetShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_column_filter_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_column_filter_help");
}
publicbooleanfilter(GameCardcard){
Arrays.fill(this.catsCount,0);
byte[]balls=card.getBalls();
for(inti=0;i<balls.length;++i){
intball=balls[i];
for(intk=1;k<=numCols;++k){
int[]col=this.colsData[k];
if(Arrays.binarySearch(col,ball)>=0){
++this.catsCount[k];
break;
}
}
}
if(this.isMode()){
//acceptmode
booleanok=true;
for(inti=1;i<this.catsCount.length;++i){
intb=this.catsCount[i];
if(Arrays.binarySearch(this.inputBalls,b)<0){
58
returnfalse;
}
}
returnthis.isMode();
}
else{
//rejectmode
for(inti=1;i<this.catsCount.length;++i){
intb=this.catsCount[i];
if(Arrays.binarySearch(this.inputBalls,b)>=0){
returnthis.isMode();
}
}
return!this.isMode();
}
}
}
/*
*AllCombinationGeneratorService.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.generator;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importbr.ufsc.inf.lagar.ui.ProgressInterface;
importjava.io.BufferedOutputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.text.NumberFormat;
importjava.util.Date;
importjava.util.zip.Deflater;
importjava.util.zip.GZIPOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipOutputStream;
publicclassAllCombinationGeneratorServiceimplementsProgressInterface{
privateCombinationGeneratorcg;
privateFilepath;
59
privateint[]numbers;
privateintnumbersPerCard;
privatebooleancancel=false;
privateintgenCount=0;
privateinttotal=0;
/**CreatesanewinstanceofAllCombinationGeneratorService*/
publicAllCombinationGeneratorService(StringsavePath,int[]numbers,int
numbersPerCard)throwsIOException{
this.path=newFile(savePath);
if(this.path.exists())this.path.delete();
this.path.createNewFile();
this.numbers=numbers;
this.numbersPerCard=numbersPerCard;
this.cg=newCombinationGenerator(this.numbers.length,this.numbersPerCard);
this.total=cg.getTotal().intValue();
}
publicvoidgenerateAllCombinations()throwsIOException{
int[]indices;
Datetoday=newDate();
FileOutputStreamfos=newFileOutputStream(this.path);
ZipOutputStreamzos=newZipOutputStream(fos);
zos.setLevel(Deflater.BEST_SPEED);
DataOutputStreamdos=newDataOutputStream(zos);
GeneratorHeaderheader=newGeneratorHeader();
header.setGameName(GameManager.getCurrentGame().getName());
header.setBallsPerCard(this.numbersPerCard);
header.setNumbers(this.numbers);
header.setNumberOfCards(this.total);
zos.putNextEntry(newZipEntry(LagarLotteryGlobals.GENERATED_HEADER_NAME));
header.saveToStream(dos);
dos.flush();
zos.closeEntry();
zos.putNextEntry(newZipEntry(LagarLotteryGlobals.GENERATED_CARDS_NAME));
byte[]balls=newbyte[this.numbersPerCard];
while(this.cg.hasMore())
{
indices=this.cg.getNext();
for(inti=0;i<indices.length;i++)
{
balls[i]=(byte)this.numbers[indices[i]];
}
dos.write(balls);
++(this.genCount);
if(this.cancel){
dos.close();
this.path.delete();
thrownewIOException("Cancelled");
60
}
}
dos.flush();
zos.closeEntry();
dos.close();
publicvoidcancel(){
this.cancel=true;
}
publicStringgetProgressText(){
NumberFormatnf=NumberFormat.getInstance();
returnnf.format(genCount)+"of"+nf.format(total)+"generated.";
}
publicintgetProgressValue(){
returnthis.genCount;
}
publicintgetMaxProgressValue(){
returnthis.total;
}
}
/*
*AllCombinationGeneratorServiceTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.core.generator;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.generator.AllCombinationGeneratorService;
importjava.util.List;
importjunit.framework.*;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.beans.XMLEncoder;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileNotFoundException;
61
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.Date;
importorg.omg.SendingContext.RunTime;
/**
*
*@authorlagar
*/
publicclassAllCombinationGeneratorServiceTestextendsTestCase{
publicAllCombinationGeneratorServiceTest(StringtestName){
super(testName);
}
/**
*TestofgenerateAllCombinationsmethod,ofclass
br.ufsc.inf.lagar.core.generator.AllCombinationGeneratorService.
*/
publicvoidtestGenerateAllCombinations()throwsIOException{
System.out.println("generateAllCombinations");
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
GameConfigurationgc=availableGames.get(1);
GameManager.setCurrentGame(gc);
AllCombinationGeneratorServiceinstance=newAllCombinationGeneratorService(
"/home/lagar/cards.llg",newint[]{1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
31,32,33,34,35},6);
instance.generateAllCombinations();
}
/*
*AllLineFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
62
importbr.ufsc.inf.lagar.filter.Filterable;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.util.Arrays;
publicclassAllLineFilterextendsAbstractGameFilter{
privateint[]inputBalls;
privateintlineSize;
privateintnumLines;
privateint[]catsCount;
/**
*CreatesanewinstanceofAllLineFilter
*/
publicAllLineFilter(){
this.lineSize=GameManager.getCurrentGame().getNumbersPerLine();
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
String[]params=input.split(Filterable.OR_SEPARATOR);
this.inputBalls=newint[params.length];
for(inti=0;i<params.length;++i){
Strings=params[i];
if(s.trim().startsWith("s=")){
try{
String[]ls=s.split("=");
this.lineSize=Integer.parseInt(ls[1].trim());
}
catch(Exceptionex){
thrownewTextInputFilterException(ex);
}
}
else{
try{
this.inputBalls[i]=Integer.parseInt(s.trim());
}
catch(NumberFormatExceptionnfex){
thrownewTextInputFilterException(nfex);
}
}
Arrays.sort(this.inputBalls);
this.numLines=GameManager.getCurrentGame().getNumbersPerCard()/
this.lineSize;
this.catsCount=newint[this.numLines];
publicStringgetShortName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_line_filter");
}
publicStringgetFullName(){
63
returnthis.getShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_line_filter_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("All_line_filter_help");
}
publicbooleanfilter(GameCardcard){
Arrays.fill(this.catsCount,0);
byte[]balls=card.getBalls();
for(inti=0;i<balls.length;++i){
intball=balls[i];
intcat=(ball1)/this.lineSize;
++catsCount[cat];//incrementsumontheline
}
if(this.isMode()){
//acceptmode
booleanok=true;
for(intb:this.catsCount){
if(Arrays.binarySearch(this.inputBalls,b)<0){
returnfalse;
}
}
returnthis.isMode();
}
else{
//rejectmode
for(intb:this.catsCount){
if(Arrays.binarySearch(this.inputBalls,b)>=0){
returnthis.isMode();
}
}
return!this.isMode();
}
}
/*
*AnalysisControlPanel.java
*
*Createdon7deJaneirode2007,19:04
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.analysis.Analysis;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameConfiguration;
64
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importbr.ufsc.inf.lagar.ui.frame.AnalysisFrame;
importbr.ufsc.inf.lagar.utils.RTSI;
importjava.awt.Dimension;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.ResourceBundle;
importjavax.swing.JOptionPane;
importjavax.swing.JScrollPane;
importjavax.swing.JTextPane;
importjavax.swing.ListModel;
importjavax.swing.event.ListDataListener;
/**
*
*@authorlagar
*/
publicclassAnalysisControlPanelextendsjavax.swing.JPanel{
publicstaticenumSourceMode{
FROM_ANALYSIS_DATABASE,
FROM_LLG_FILE
}
privateSourceModesourceMode=SourceMode.FROM_ANALYSIS_DATABASE;
/**
*CreatesnewformAnalysisControlPanel
*/
privateGameConfigurationcurrentGame=null;
publicAnalysisControlPanel(){
initComponents();
this.currentGame=GameManager.getCurrentGame();
this.updateMaxCardsResultsDb(currentGame.getGameResults().getLoadedResults().
size());
this.fileChooserLLG1.setMode(FileChooserLLG.ChooserMode.LOAD_MODE);
this.statusLabel.setVisible(false);
}
publicvoidupdateMaxCardsResultsDb(intcards){
this.toField.setText(String.valueOf(cards));
}
privatevoidprocessInfoButton(){
Analysisanalysis=(Analysis)this.analysisList.getSelectedValue();
if(analysis!=null){
Stringinfo=analysis.getHelpInfo();
DecisionDialogdd=newDecisionDialog(null,false);
JTextPanetextPane=newJTextPane();
textPane.setText(info);
JScrollPanepane=newJScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dd.getMainPanel().add(pane,pane.getClass().getName());
dd.getButtonsPanel().setVisible(false);
dd.getTitlePanel().setTitle(analysis.getName());
65
dd.setTitle(ResourceBundle.getBundle("resources/bundles/lagarLottery").ge
tString("Help"));
dd.setVisible(true);
}
}
privatevoidprocessRunButton(){
intfromRes=1;
inttoRes=1;
intjumpRes=1;
GenCardIOgenCardIO=null;
if(this.sourceMode==SourceMode.FROM_ANALYSIS_DATABASE){
try{
fromRes=Integer.parseInt(this.fromField.getText());
toRes=Integer.parseInt(this.toField.getText());
jumpRes=Integer.parseInt(this.jumpField.getText());
}
catch(Exceptionex){
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Results_range_contains_invalid_data"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
if(fromRes<0||toRes<0||jumpRes<0){
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Results_range_contains_invalid_data"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
if(this.currentGame.getGameResults().getLoadedResults().size()==0){
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("You_don't_have_any_loaded_results."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
}
else{
try{
genCardIO=newGenCardIO(new
File(this.fileChooserLLG1.getFilePath()));
}catch(IOExceptionex){
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Invalid_LLG_file."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
}
66
finalAnalysisanalysis=(Analysis)this.analysisList.getSelectedValue();
if(analysis!=null){
analysis.setBegin(fromRes);
analysis.setEnd(toRes);
analysis.setJump(jumpRes);
analysis.setSourceMode(this.sourceMode);
analysis.setGenCardIO(genCardIO);
analysis.setCurrentGameConfiguration(this.currentGame);
this.statusLabel.setText(java.util.ResourceBundle.getBundle("resources/bu
ndles/lagarLottery").getString("Loading_")+analysis.getName()+"
"+java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("_in
_background.."));
Threadt=newThread(){
publicvoidrun(){
finalAnalysisFrameframe=newAnalysisFrame(analysis);
frame.setLocationRelativeTo(null);
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setPreferredSize(newDimension(800,600));
frame.setSize(newDimension(800,600));
frame.showAnalysis();
}
};
t.start();
}
}
publicvoidfillAvailableAnalysis()throwsException{
finalList<Analysis>all=newArrayList<Analysis>();
StringpackageName="br.ufsc.inf.lagar.analysis.gameanalysis";
ArrayList<String>classes=RTSI.find(packageName,Analysis.class);
for(Stringclazz:classes){
clazz=packageName+"."+clazz;
Analysisanalysis=(Analysis)Class.forName(clazz).newInstance();
all.add(analysis);
}
this.analysisList.setModel(newListModel(){
publicvoidaddListDataListener(ListDataListenerl){
}
publicObjectgetElementAt(intindex){
returnall.get(index);
}
publicintgetSize(){
returnall.size();
}
publicvoidremoveListDataListener(ListDataListenerl){
}
});
this.analysisList.setSelectedIndex(0);
privatevoidprocessAllCheckBox(){
if(this.allResultsCheckBox.isSelected()){
67
this.toField.setText(String.valueOf(currentGame.getGameResults().getLoade
dResults().size()));
this.fromField.setText("1");
this.jumpField.setText("1");
this.fromLabel.setEnabled(false);
this.fromField.setEnabled(false);
this.toLabel.setEnabled(false);
this.toField.setEnabled(false);
this.jumpLabel.setEnabled(false);
this.jumpField.setEnabled(false);
}
else{
this.fromLabel.setEnabled(true);
this.fromField.setEnabled(true);
this.toLabel.setEnabled(true);
this.toField.setEnabled(true);
this.jumpLabel.setEnabled(true);
this.jumpField.setEnabled(true);
}
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
buttonGroup1=newjavax.swing.ButtonGroup();
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
mainPanel=newjavax.swing.JPanel();
rangePanel=newjavax.swing.JPanel();
fromLabel=newjavax.swing.JLabel();
fromField=newjavax.swing.JTextField();
toLabel=newjavax.swing.JLabel();
toField=newjavax.swing.JTextField();
allResultsCheckBox=newjavax.swing.JCheckBox();
jumpLabel=newjavax.swing.JLabel();
jumpField=newjavax.swing.JTextField();
resultsRadio=newjavax.swing.JRadioButton();
llgRadio=newjavax.swing.JRadioButton();
fileChooserLLG1=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
availablePanel=newjavax.swing.JPanel();
scrollPane=newjavax.swing.JScrollPane();
analysisList=newjavax.swing.JList();
runButton=newjavax.swing.JButton();
infoButton=newjavax.swing.JButton();
labelSepLeft=newjavax.swing.JLabel();
labelSepRight=newjavax.swing.JLabel();
statusPanel=newjavax.swing.JPanel();
statusLabel=newjavax.swing.JLabel();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
simpleInternalFrame1.setTitle(bundle.getString("Analysis"));//NOI18N
rangePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getS
tring("Range")));//NOI18N
rangePanel.setToolTipText(bundle.getString("Only_affects_new_analysis"));//
NOI18N
fromLabel.setText(bundle.getString("From_result"));//NOI18N
68
fromLabel.setEnabled(false);
fromField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
fromField.setText("1");
fromField.setEnabled(false);
toLabel.setText(bundle.getString("to"));//NOI18N
toLabel.setEnabled(false);
toField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
toField.setText("10000");
toField.setEnabled(false);
allResultsCheckBox.setSelected(true);
allResultsCheckBox.setText(bundle.getString("All_results"));//NOI18N
allResultsCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,
0,0,0));
allResultsCheckBox.setMargin(newjava.awt.Insets(0,0,0,0));
allResultsCheckBox.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
allResultsCheckBoxActionPerformed(evt);
}
});
jumpLabel.setText(bundle.getString("Jump_results_by"));//NOI18N
jumpLabel.setEnabled(false);
jumpField.setColumns(4);
jumpField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jumpField.setText("1");
jumpField.setEnabled(false);
buttonGroup1.add(resultsRadio);
resultsRadio.setSelected(true);
resultsRadio.setText(bundle.getString("Analysis_from_results_database"));//
NOI18N
resultsRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,
0));
resultsRadio.setMargin(newjava.awt.Insets(0,0,0,0));
resultsRadio.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
resultsRadioActionPerformed(evt);
}
});
buttonGroup1.add(llgRadio);
llgRadio.setText(bundle.getString("Analysis_from_generated_game_(.LLG)"));//
NOI18N
llgRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
llgRadio.setMargin(newjava.awt.Insets(0,0,0,0));
llgRadio.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
llgRadioActionPerformed(evt);
}
});
fileChooserLLG1.setEnabled(false);
org.jdesktop.layout.GroupLayoutrangePanelLayout=new
org.jdesktop.layout.GroupLayout(rangePanel);
rangePanel.setLayout(rangePanelLayout);
rangePanelLayout.setHorizontalGroup(
rangePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEAD
ING)
69
.add(rangePanelLayout.createSequentialGroup()
.addContainerGap()
.add(rangePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLa
yout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
rangePanelLayout.createSequentialGroup()
.add(17,17,17)
.add(fileChooserLLG1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,481,Short.MAX_VALUE))
.add(rangePanelLayout.createSequentialGroup()
.add(17,17,17)
.add(rangePanelLayout.createParallelGroup(org.jdesktop.layout
.GroupLayout.LEADING)
.add(allResultsCheckBox)
.add(rangePanelLayout.createSequentialGroup()
.add(rangePanelLayout.createParallelGroup(org.jdeskto
p.layout.GroupLayout.TRAILING)
.add(fromLabel)
.add(jumpLabel))
.add(rangePanelLayout.createParallelGroup(org.jdeskto
p.layout.GroupLayout.LEADING,false)
.add(rangePanelLayout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutSt
yle.RELATED)
.add(fromField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,50,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(rangePanelLayout.createSequentialGroup()
.add(5,5,5)
.add(jumpField)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELA
TED)
.add(toLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELA
TED)
.add(toField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,45,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.add(resultsRadio)
.add(llgRadio))
.addContainerGap())
);
rangePanelLayout.linkSize(newjava.awt.Component[]{fromField,toField},
org.jdesktop.layout.GroupLayout.HORIZONTAL);
rangePanelLayout.setVerticalGroup(
rangePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEAD
ING)
.add(rangePanelLayout.createSequentialGroup()
.add(resultsRadio)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(allResultsCheckBox)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(rangePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLa
yout.BASELINE)
.add(fromLabel)
.add(fromField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(toLabel)
.add(toField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
70
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(rangePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLa
yout.BASELINE)
.add(jumpLabel)
.add(jumpField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(llgRadio)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
rangePanelLayout.linkSize(newjava.awt.Component[]{fromField,toField},
org.jdesktop.layout.GroupLayout.VERTICAL);
availablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.
getString("Available_analysis")));//NOI18N
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZ
ONTAL_SCROLLBAR_NEVER);
analysisList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION
);
analysisList.addListSelectionListener(new
javax.swing.event.ListSelectionListener(){
publicvoidvalueChanged(javax.swing.event.ListSelectionEventevt){
analysisListValueChanged(evt);
}
});
scrollPane.setViewportView(analysisList);
runButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
runButton.setText(bundle.getString("Run"));//NOI18N
runButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
runButtonActionPerformed(evt);
}
});
infoButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/info.png")));
infoButton.setText(bundle.getString("Info"));//NOI18N
infoButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
infoButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutstatusPanelLayout=new
org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
DING)
.add(statusLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,498,
Short.MAX_VALUE)
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
71
DING)
.add(statusLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,44,
Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayoutavailablePanelLayout=new
org.jdesktop.layout.GroupLayout(availablePanel);
availablePanel.setLayout(availablePanelLayout);
availablePanelLayout.setHorizontalGroup(
availablePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.
LEADING)
.add(availablePanelLayout.createSequentialGroup()
.addContainerGap()
.add(availablePanelLayout.createParallelGroup(org.jdesktop.layout.Gro
upLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
availablePanelLayout.createSequentialGroup()
.add(labelSepLeft,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,155,Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(runButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(infoButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(labelSepRight,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,155,Short.MAX_VALUE))
.add(scrollPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
498,Short.MAX_VALUE)
.add(statusPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
.addContainerGap())
);
availablePanelLayout.linkSize(newjava.awt.Component[]{infoButton,
runButton},org.jdesktop.layout.GroupLayout.HORIZONTAL);
availablePanelLayout.setVerticalGroup(
availablePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.
LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
availablePanelLayout.createSequentialGroup()
.add(scrollPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,120,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(statusPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(availablePanelLayout.createParallelGroup(org.jdesktop.layout.Gro
upLayout.LEADING)
.add(availablePanelLayout.createParallelGroup(org.jdesktop.layout
.GroupLayout.BASELINE)
.add(runButton)
.add(infoButton))
.add(labelSepLeft,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(labelSepRight,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
availablePanelLayout.linkSize(newjava.awt.Component[]{infoButton,
72
runButton},org.jdesktop.layout.GroupLayout.VERTICAL);
availablePanelLayout.linkSize(newjava.awt.Component[]{labelSepLeft,
labelSepRight},org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayoutmainPanelLayout=new
org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(availablePanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(rangePanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
mainPanelLayout.createSequentialGroup()
.add(rangePanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(availablePanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,mainPanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,532,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
}//</editorfold>//GENEND:initComponents
privatevoidllgRadioActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_llgRadioActionPerformed
this.sourceMode=SourceMode.FROM_LLG_FILE;
this.allResultsCheckBox.setEnabled(false);
this.fromLabel.setEnabled(false);
this.fromField.setEnabled(false);
this.toLabel.setEnabled(false);
this.toField.setEnabled(false);
this.jumpLabel.setEnabled(false);
this.jumpField.setEnabled(false);
73
this.fileChooserLLG1.setEnabled(true);
}//GENLAST:event_llgRadioActionPerformed
privatevoidresultsRadioActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_resultsRadioActionPerformed
this.sourceMode=SourceMode.FROM_ANALYSIS_DATABASE;
this.allResultsCheckBox.setEnabled(true);
if(!this.allResultsCheckBox.isSelected()){
this.fromLabel.setEnabled(true);
this.fromField.setEnabled(true);
this.toLabel.setEnabled(true);
this.toField.setEnabled(true);
this.jumpLabel.setEnabled(true);
this.jumpField.setEnabled(true);
}
this.fileChooserLLG1.setEnabled(false);
}//GENLAST:event_resultsRadioActionPerformed
privatevoidanalysisListValueChanged(javax.swing.event.ListSelectionEventevt)
{//GENFIRST:event_analysisListValueChanged
}//GENLAST:event_analysisListValueChanged
privatevoidinfoButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_infoButtonActionPerformed
this.processInfoButton();
}//GENLAST:event_infoButtonActionPerformed
privatevoidrunButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_runButtonActionPerformed
this.processRunButton();
}//GENLAST:event_runButtonActionPerformed
privatevoidallResultsCheckBoxActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_allResultsCheckBoxActionPerformed
this.processAllCheckBox();
}//GENLAST:event_allResultsCheckBoxActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JCheckBoxallResultsCheckBox;
privatejavax.swing.JListanalysisList;
privatejavax.swing.JPanelavailablePanel;
privatejavax.swing.ButtonGroupbuttonGroup1;
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserLLG1;
privatejavax.swing.JTextFieldfromField;
privatejavax.swing.JLabelfromLabel;
privatejavax.swing.JButtoninfoButton;
privatejavax.swing.JTextFieldjumpField;
privatejavax.swing.JLabeljumpLabel;
privatejavax.swing.JLabellabelSepLeft;
privatejavax.swing.JLabellabelSepRight;
privatejavax.swing.JRadioButtonllgRadio;
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JPanelrangePanel;
privatejavax.swing.JRadioButtonresultsRadio;
privatejavax.swing.JButtonrunButton;
privatejavax.swing.JScrollPanescrollPane;
74
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
privatejavax.swing.JLabelstatusLabel;
privatejavax.swing.JPanelstatusPanel;
privatejavax.swing.JTextFieldtoField;
privatejavax.swing.JLabeltoLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*AnalysisFrame.java
*
*Createdon15deJaneirode2007,23:22
*/
packagebr.ufsc.inf.lagar.ui.frame;
importbr.ufsc.inf.lagar.analysis.Analysis;
importjava.util.List;
importjavax.swing.JPanel;
/**
*
*@authorlagar
*/
publicclassAnalysisFrameextendsjavax.swing.JFrame{
privateAnalysisanalysis;
/**CreatesnewformAnalysisFrame*/
publicAnalysisFrame(Analysisanalysis){
this.analysis=analysis;
initComponents();
this.setTitle(analysis.getName());
}
publicvoidshowAnalysis(){
this.analysis.calculateAnalysis();
List<JPanel>panels=this.analysis.getPanels();
for(JPanelpanel:panels){
if(panel!=null){
this.tabsPane.addTab(panel.getName(),panel);
}
}
this.setVisible(true);
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
mainPanel=newjavax.swing.JPanel();
tabsPane=newjavax.swing.JTabbedPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.layout.GroupLayoutmainPanelLayout=new
org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
75
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(tabsPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,527,
Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(org.jdesktop.layout.GroupLayout.TRAILING,tabsPane,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,346,Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
pack();
}//</editorfold>//GENEND:initComponents
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JTabbedPanetabsPane;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*Analysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCardIterator;
importbr.ufsc.inf.lagar.main.GameResultIterator;
76
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.ui.panels.AnalysisControlPanel;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjavax.swing.JPanel;
publicabstractclassAnalysis{
privateGameConfigurationcurrentGameConfiguration;
privateintbegin;
privateintend;
privateintjump;
privateAnalysisControlPanel.SourceModesourceMode;
privateGenCardIOgenCardIO;
publicGameConfigurationgetCurrentGameConfiguration(){
returncurrentGameConfiguration;
}
publicvoidsetCurrentGameConfiguration(GameConfiguration
currentGameConfiguration){
this.currentGameConfiguration=currentGameConfiguration;
}
publicGameCardIteratorgetGameCardIterator(){
if(this.sourceMode==sourceMode.FROM_ANALYSIS_DATABASE)
returnthis.getCurrentGameConfiguration().getGameCardIterator(begin,end,
jump);
if(this.sourceMode==sourceMode.FROM_LLG_FILE){
returnthis.genCardIO;
}
thrownewRuntimeException("ErroringetGameCardIterator");
}
publicabstractvoidcalculateAnalysis();
publicabstractList<JPanel>getPanels();
publicabstractStringgetName();
publicabstractStringgetHelpInfo();
publicbooleanacceptGame(StringgameName){
returntrue;
}
@Override
publicStringtoString(){
returnthis.getName();
}
publicfinalvoidsetBegin(intbegin){
this.begin=begin;
}
publicfinalvoidsetEnd(intend){
this.end=end;
}
77
publicfinalvoidsetJump(intjump){
this.jump=jump;
}
publicfinalvoidsetSourceMode(AnalysisControlPanel.SourceModemode){
this.sourceMode=mode;
}
publicfinalvoidsetGenCardIO(GenCardIOgenCardIO){
this.genCardIO=genCardIO;
}
}
/*
*Animated1Frame.java
*
*Createdon20deJaneirode2005,04:09
*/
/**
*
*@authorlagar
*/
packagebr.ufsc.inf.lagar.verify.animated1;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.verify.VerificatorInterface;
importjava.io.*;
importjava.net.*;
importjava.util.List;
publicclassAnimated1Frameextendsjavax.swing.JFrame{
privateBall[]matrix;
privateintlastNumber;
privateintcurrentCard;
privateinthits;
privateintcurrentDrw;
privateGenCardIObetcards;
privateGameCardresult;
privateGameCardbuffer;
/**
*CreatesnewformAnimated1Frame
*/
publicAnimated1Frame(FilellgFile)throwsIOException{
this.initComponents();
this.setLastNumber(1);
this.currentCard=0;
this.hits=0;
this.currentDrw=0;
this.betcards=newGenCardIO(llgFile);
this.limitLabel.setText("/"+(this.getBetcards().size()));
this.buffer=newGameCard(0,null,this.betcards.getBallsPerCard());
78
this.inicializaMatriz();
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
jPanel1=newjavax.swing.JPanel();
jLabel1=newjavax.swing.JLabel();
numbersLabel=newjavax.swing.JLabel();
nextButton=newjavax.swing.JButton();
enterButton=newjavax.swing.JButton();
warnLabel=newjavax.swing.JLabel();
jLabel2=newjavax.swing.JLabel();
currentDrwLabel=newjavax.swing.JLabel();
summaryButton=newjavax.swing.JButton();
jLabel3=newjavax.swing.JLabel();
hitsLabel=newjavax.swing.JLabel();
actualLabel=newjavax.swing.JLabel();
jLabel4=newjavax.swing.JLabel();
limitLabel=newjavax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("LotomaniaCartoes");
addWindowListener(newjava.awt.event.WindowAdapter(){
publicvoidwindowClosing(java.awt.event.WindowEventevt){
exitForm(evt);
}
});
jPanel1.setLayout(newjava.awt.GridLayout(10,10,4,3));
jPanel1.setAlignmentX(0.0F);
jPanel1.setAlignmentY(0.0F);
jPanel1.addKeyListener(newjava.awt.event.KeyAdapter(){
publicvoidkeyPressed(java.awt.event.KeyEventevt){
jPanel1KeyPressed(evt);
}
});
jLabel1.setFont(newjava.awt.Font("Dialog",0,12));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel1.setText("Markednumbers");
numbersLabel.setFont(newjava.awt.Font("Dialog",1,14));
numbersLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
numbersLabel.setText("0");
nextButton.setText("Next");
nextButton.setEnabled(false);
nextButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
nextButtonActionPerformed(evt);
}
});
enterButton.setText("Enterres");
enterButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
79
enterButtonActionPerformed(evt);
}
});
warnLabel.setFont(newjava.awt.Font("Dialog",1,14));
warnLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setFont(newjava.awt.Font("Dialog",0,12));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel2.setText("Current=");
currentDrwLabel.setFont(newjava.awt.Font("Dialog",1,14));
currentDrwLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
currentDrwLabel.setText("0");
summaryButton.setText("Summary");
summaryButton.setEnabled(false);
summaryButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
summaryButtonActionPerformed(evt);
}
});
jLabel3.setFont(newjava.awt.Font("Dialog",1,14));
jLabel3.setText("HITS=");
hitsLabel.setFont(newjava.awt.Font("Dialog",0,18));
hitsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hitsLabel.setText("0");
actualLabel.setFont(newjava.awt.Font("Dialog",1,14));
actualLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
actualLabel.setText("0");
jLabel4.setFont(newjava.awt.Font("Dialog",0,12));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setText("curr");
limitLabel.setFont(newjava.awt.Font("Dialog",1,14));
limitLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
limitLabel.setText("/x");
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(300,300,300)
.add(warnLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,210,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(100,100,100)
.add(jLabel3,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,90,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(hitsLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,50,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(10,10,10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayo
ut.LEADING)
80
.add(layout.createSequentialGroup()
.add(130,130,130)
.add(numbersLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jLabel1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,140,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(30,30,30)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayo
ut.LEADING)
.add(layout.createSequentialGroup()
.add(70,70,70)
.add(currentDrwLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jLabel2,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,80,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
370,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(20,20,20)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(enterButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
100,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(nextButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
100,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(summaryButton,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,100,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(20,20,20)
.add(jLabel4,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
50,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(30,30,30)
.add(limitLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,50,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(actualLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
50,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(warnLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(jLabel3,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(hitsLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
40,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayo
ut.LEADING)
.add(layout.createParallelGroup(org.jdesktop.layout.Group
Layout.LEADING)
.add(numbersLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
81
.add(jLabel1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.Group
Layout.LEADING)
.add(currentDrwLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel2,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
300,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(20,20,20)
.add(enterButton)
.add(45,45,45)
.add(nextButton)
.add(15,15,15)
.add(summaryButton)
.add(5,5,5)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayo
ut.LEADING)
.add(layout.createSequentialGroup()
.add(30,30,30)
.add(jLabel4,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,30,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(limitLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(actualLabel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,40,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
);
java.awt.DimensionscreenSize=
java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width521)/2,(screenSize.height455)/2,521,455);
}//</editorfold>//GENEND:initComponents
privatevoidsummaryButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_summaryButtonActionPerformed
//this.ma1.mostraSumario();
//System.out.println(ma1.buffer);
}//GENLAST:event_summaryButtonActionPerformed
privatevoidenterButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_enterButtonActionPerformed
GameConfigurationgc=GameManager.getCurrentGame();
try{
if(Ball.countNumbers==gc.getNumbersPerDrawing()){
this.getWarnLabel().setText("OK!");
int[]res=newint[gc.getNumbersPerDrawing()];
intindex=0;
for(inti=1;i<this.getMatrix().length;i++){
82
if(getMatrix()[i].isState()){
res[index]=getMatrix()[i].getNumber();
index++;
this.result=newGameCard(0,null,gc.getNumbersPerDrawing());
for(inti=0;i<res.length;++i){
this.result.setBall((byte)res[i],i);
}
this.getNextButton().setEnabled(true);
this.summaryButton.setEnabled(true);
//ma1=newMostraAcertos(resultado,gerado1);
}
else{
this.getWarnLabel().setText("Lessthan"+gc.getNumbersPerDrawing());
}
catch(Exceptionex){
this.getWarnLabel().setText("Exception!");
}//GENLAST:event_enterButtonActionPerformed
privatevoidnextButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_nextButtonActionPerformed
GameConfigurationgc=GameManager.getCurrentGame();
this.getNextButton().setEnabled(false);
Ball.countNumbers=0;
for(inti=1;i<this.getMatrix().length;i++){
this.getMatrix()[i].restart();
for(inti=0;i<this.result.getBalls().length;i++){
this.getMatrix()[this.result.getBalls()[i]].btClick();
this.setLastNumber(1);
this.currentDrwLabel.setText("0");
this.currentDrw=0;
this.hits=0;
this.getHitsLabel().setText("0");
Ball.countNumbers=this.getBetcards().getBallsPerCard();
83
this.getNumbersLabel().setText(String.valueOf(this.getBetcards().getBallsPerC
ard()));
this.incrementCurrentCard();
this.getWarnLabel().setText("");
if(this.currentCard<this.getBetcards().size()){
AnimateResanima=newAnimateRes(this);
anima.start();
}
else{
this.getWarnLabel().setText("Gameover!");
}//GENLAST:event_nextButtonActionPerformed
privatevoidjPanel1KeyPressed(java.awt.event.KeyEventevt){//GEN
FIRST:event_jPanel1KeyPressed
StringTexto=evt.getKeyText(evt.getKeyCode());
if(Texto.equals("Left"))
{
try{
this.getMatrix()[this.getLastNumber()1].requestFocus();
this.setLastNumber(this.getLastNumber()1);
}
catch(Exceptionex){
this.setLastNumber(this.getLastNumber()+1);
}
else
{
if(Texto.equals("Right"))
{
try{
this.getMatrix()[this.getLastNumber()+1].requestFocus();
this.setLastNumber(this.getLastNumber()+1);
}
catch(Exceptionex){
this.setLastNumber(this.getLastNumber()1);
}
else
{
if(Texto.equals("Up"))
{
try{
this.getMatrix()[this.getLastNumber()10].requestFocus();
this.setLastNumber(this.getLastNumber()10);
}
catch(Exceptionex){
84
this.setLastNumber(this.getLastNumber()+10);
}
}
else
{
if(Texto.equals("Down"))
{
try{
this.getMatrix()[this.getLastNumber()+10].requestFocu
s();
this.setLastNumber(this.getLastNumber()+10);
}
catch(Exceptionex){
this.setLastNumber(this.getLastNumber()10);
}
}
}
}
}
//}//Endif_Condio_GETTEXT
}//GENLAST:event_jPanel1KeyPressed
publicvoidincrementHits(){
this.hits++;
this.getHitsLabel().setText(String.valueOf(this.getHits()));
publicvoidincrementDrw(){
this.currentDrw++;
this.currentDrwLabel.setText(String.valueOf(this.getCurrentDrw()));
privatevoidincrementCurrentCard(){
this.currentCard++;
this.actualLabel.setText(String.valueOf(this.currentCard));
publicbyte[]getCurrentBalls(){
try{
this.betcards.skipToCard(this.buffer,this.currentCard);
}catch(IOExceptionex){
ex.printStackTrace();
thrownewRuntimeException(ex);
}
returnthis.buffer.getBalls();
}
privatevoidinicializaMatriz(){
intbs=GameManager.getCurrentGame().getNumbersPerCard();
85
this.matrix=newBall[bs+1];
for(inti=1;i<this.getMatrix().length;i++){
this.getMatrix()[i]=newBall(i,this);
this.getJPanel1().add(this.getMatrix()[i]);
publicBall[]getMatrix(){
returnmatrix;
}
publicGenCardIOgetBetcards(){
returnbetcards;
}
publicjavax.swing.JLabelgetHitsLabel(){
returnhitsLabel;
}
publicjavax.swing.JButtongetNextButton(){
returnnextButton;
}
publicjavax.swing.JLabelgetWarnLabel(){
returnwarnLabel;
}
publicintgetCurrentDrw(){
returncurrentDrw;
}
publicjavax.swing.JPanelgetJPanel1(){
returnjPanel1;
}
publicjavax.swing.JLabelgetNumbersLabel(){
returnnumbersLabel;
}
publicintgetLastNumber(){
returnlastNumber;
}
publicvoidsetLastNumber(intlastNumber){
this.lastNumber=lastNumber;
}
/**ExittheApplication*/
privatevoidexitForm(java.awt.event.WindowEventevt){//GENFIRST:event_exitForm
//this.dispose();
}//GENLAST:event_exitForm
publicstaticvoidmain(String[]args)throwsIOException{
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
GameConfigurationgc=availableGames.get(0);
gc.getGameResults().loadResults();
86
GameManager.setCurrentGame(gc);
Filef=newFile("/home/lagar/teste/1ateh10.llg");
newAnimated1Frame(f).setVisible(true);
}
publicintgetHits(){
returnhits;
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JLabelactualLabel;
privatejavax.swing.JLabelcurrentDrwLabel;
privatejavax.swing.JButtonenterButton;
privatejavax.swing.JLabelhitsLabel;
privatejavax.swing.JLabeljLabel1;
privatejavax.swing.JLabeljLabel2;
privatejavax.swing.JLabeljLabel3;
privatejavax.swing.JLabeljLabel4;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JLabellimitLabel;
privatejavax.swing.JButtonnextButton;
privatejavax.swing.JLabelnumbersLabel;
privatejavax.swing.JButtonsummaryButton;
privatejavax.swing.JLabelwarnLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*AnimateRes.java
*
*Createdon3deNovembrode2004,03:19
*/
/**
*
*@authorlagar
*/
packagebr.ufsc.inf.lagar.verify.animated1;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.awt.*;
importjava.io.IOException;
importjavax.swing.*;
importjava.util.*;
publicclassAnimateResextendsThread{
Animated1FrameanimatedFrame;
privateintdelay=0;
intemotion;
privateBeepsbeep;
/**
*CreatesanewinstanceofAnimateRes
*/
publicAnimateRes(Animated1Frameaf){
this.animatedFrame=af;
this.emotion=GameManager.getCurrentGame().getNumbersPerDrawing()3;
try{
87
this.beep=newBeeps();
}catch(IOExceptionex){
ex.printStackTrace();
}
}
publicvoidrun(){
Ball[]matrix=this.animatedFrame.getMatrix();
byte[]oRes=animatedFrame.getCurrentBalls();
Integer[]resres=newInteger[oRes.length];
for(inti=0;i<resres.length;i++)
resres[i]=Integer.valueOf(oRes[i]);
Collections.shuffle(Arrays.asList(resres));
for(intj=0;j<resres.length;j++){
intnum=resres[j].intValue();
if(matrix[num].isState()){
this.beep.beep();
matrix[num].blue();
this.sleepUtil(50);
matrix[num].red();
this.beep.goodBeep();
this.animatedFrame.incrementHits();
//this.sleepUtil(150);
}
else{
this.beep.beep();
matrix[num].blue();
this.animatedFrame.incrementDrw();
if(animatedFrame.getHits()>=emotion&&(j!=resres.length1)){
animatedFrame.getWarnLabel().setText("Almostthere!!");
this.sleepUtil(this.getDelay()+2400);
}
else{
this.sleepUtil(this.getDelay());
animatedFrame.getWarnLabel().setText("");
this.animatedFrame.getNextButton().setEnabled(true);
88
}
privatevoidsleepUtil(inttime){
if(time==0)return;
try{
Thread.sleep(time);
}
catch(Exceptionioex){System.out.println(ioex.getMessage());}
publicintgetDelay(){
returndelay;
}
publicvoidsetDelay(intdelay){
this.delay=delay;
}
packagebr.ufsc.inf.lagar.verify.animated1.osc;
/*
*AudioCommon.java
*
*Thisfileispartofjsresources.org
*/
/*
*Copyright(c)19992001byMatthiasPfisterer
*Allrightsreserved.
*
*Redistributionanduseinsourceandbinaryforms,withorwithout
*modification,arepermittedprovidedthatthefollowingconditions
*aremet:
*
*Redistributionsofsourcecodemustretaintheabovecopyrightnotice,
*thislistofconditionsandthefollowingdisclaimer.
*Redistributionsinbinaryformmustreproducetheabovecopyright
*notice,thislistofconditionsandthefollowingdisclaimerinthe
*documentationand/orothermaterialsprovidedwiththedistribution.
*
*THISSOFTWAREISPROVIDEDBYTHECOPYRIGHTHOLDERSANDCONTRIBUTORS
*"ASIS"ANDANYEXPRESSORIMPLIEDWARRANTIES,INCLUDING,BUTNOT
*LIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESS
*FORAPARTICULARPURPOSEAREDISCLAIMED.INNOEVENTSHALLTHE
*COPYRIGHTOWNERORCONTRIBUTORSBELIABLEFORANYDIRECT,INDIRECT,
*INCIDENTAL,SPECIAL,EXEMPLARY,ORCONSEQUENTIALDAMAGES
*(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENTOFSUBSTITUTEGOODSOR
*SERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION)
*HOWEVERCAUSEDANDONANYTHEORYOFLIABILITY,WHETHERINCONTRACT,
*STRICTLIABILITY,ORTORT(INCLUDINGNEGLIGENCEOROTHERWISE)
*ARISINGINANYWAYOUTOFTHEUSEOFTHISSOFTWARE,EVENIFADVISED
*OFTHEPOSSIBILITYOFSUCHDAMAGE.
*/
/*
|<thiscodeisformattedtofitinto80columns>|
*/
importjavax.sound.sampled.AudioFileFormat;
89
importjavax.sound.sampled.AudioFormat;
importjavax.sound.sampled.AudioSystem;
importjavax.sound.sampled.DataLine;
importjavax.sound.sampled.Line;
importjavax.sound.sampled.LineUnavailableException;
importjavax.sound.sampled.Mixer;
importjavax.sound.sampled.SourceDataLine;
importjavax.sound.sampled.TargetDataLine;
/**Commonmethodsforaudioexamples.
*/
publicclassAudioCommon
{
privatestaticbooleanDEBUG=false;
publicstaticvoidsetDebug(booleanbDebug)
{
DEBUG=bDebug;
}
/**TODO:
*/
publicstaticvoidlistSupportedTargetTypes()
{
StringstrMessage="Supportedtargettypes:";
AudioFileFormat.Type[]aTypes=AudioSystem.getAudioFileTypes();
for(inti=0;i<aTypes.length;i++)
{
strMessage+=""+aTypes[i].getExtension();
}
out(strMessage);
}
/**Tryingtogetanaudiofiletypeforthepassedextension.
Thisworksbyexaminingallavailablefiletypes.Foreach
type,iftheextensionthistypepromissestohandlematches
theextensionwearetryingtofindatypefor,thistypeis
returned.
Ifnoappropriatetypeisfound,nullisreturned.
*/
publicstaticAudioFileFormat.TypefindTargetType(StringstrExtension)
{
AudioFileFormat.Type[]aTypes=AudioSystem.getAudioFileTypes();
for(inti=0;i<aTypes.length;i++)
{
if(aTypes[i].getExtension().equals(strExtension))
{
returnaTypes[i];
}
}
returnnull;
}
90
/**TODO:
*/
publicstaticvoidlistMixersAndExit()
{
out("AvailableMixers:");
Mixer.Info[]aInfos=AudioSystem.getMixerInfo();
for(inti=0;i<aInfos.length;i++)
{
out(aInfos[i].getName());
}
if(aInfos.length==0)
{
out("[Nomixersavailable]");
}
System.exit(0);
}
/**ListMixers.
OnlyMixersthatsupporteitherTargetDataLinesorSourceDataLines
arelisted,dependingonthevalueofbPlayback.
*/
publicstaticvoidlistMixersAndExit(booleanbPlayback)
{
out("AvailableMixers:");
Mixer.Info[]aInfos=AudioSystem.getMixerInfo();
for(inti=0;i<aInfos.length;i++)
{
Mixermixer=AudioSystem.getMixer(aInfos[i]);
Line.InfolineInfo=newLine.Info(bPlayback?
SourceDataLine.class:
TargetDataLine.class);
if(mixer.isLineSupported(lineInfo))
{
out(aInfos[i].getName());
}
}
if(aInfos.length==0)
{
out("[Nomixersavailable]");
}
System.exit(0);
}
/**TODO:
ThismethodtriestoreturnaMixer.Infowhosename
matchesthepassedname.IfnomatchingMixer.Infois
found,nullisreturned.
*/
publicstaticMixer.InfogetMixerInfo(StringstrMixerName)
{
Mixer.Info[]aInfos=AudioSystem.getMixerInfo();
for(inti=0;i<aInfos.length;i++)
{
if(aInfos[i].getName().equals(strMixerName))
{
returnaInfos[i];
}
91
}
returnnull;
}
/**TODO:
*/
publicstaticTargetDataLinegetTargetDataLine(StringstrMixerName,
AudioFormataudioFormat,
intnBufferSize)
{
/*
Askingforalineisarathertrickything.
WehavetoconstructanInfoobjectthatspecifies
thedesiredpropertiesfortheline.
First,wehavetosaywhichkindoflinewewant.The
possibilitiesare:SourceDataLine(forplayback),Clip
(forrepeatedplayback)andTargetDataLine(for
recording).
Here,wewanttodonormalcapture,soweaskfor
aTargetDataLine.
Then,wehavetopassanAudioFormatobject,sothat
theLineknowswhichformatthedatapassedtoit
willhave.
Furthermore,wecangiveJavaSoundahintabouthow
bigtheinternalbufferforthelineshouldbe.This
isn'tusedhere,signalingthatwe
don'tcareabouttheexactsize.JavaSoundwilluse
somedefaultvalueforthebuffersize.
*/
TargetDataLinetargetDataLine=null;
DataLine.Infoinfo=newDataLine.Info(TargetDataLine.class,
audioFormat,nBufferSize);
try
{
if(strMixerName!=null)
{
Mixer.InfomixerInfo=
getMixerInfo(strMixerName);
if(mixerInfo==null)
{
out("AudioCommon.getTargetDataLine():mixer
notfound:"+strMixerName);
returnnull;
}
Mixermixer=AudioSystem.getMixer(mixerInfo);
targetDataLine=(TargetDataLine)
mixer.getLine(info);
}
else
{
if(DEBUG){out("AudioCommon.getTargetDataLine():
usingdefaultmixer");}
targetDataLine=(TargetDataLine)
AudioSystem.getLine(info);
}
/*
*Thelineisthere,butitisnotyetreadyto
*receiveaudiodata.Wehavetoopentheline.
*/
if(DEBUG){out("AudioCommon.getTargetDataLine():opening
line...");}
92
targetDataLine.open(audioFormat,nBufferSize);
if(DEBUG){out("AudioCommon.getTargetDataLine():opened
line");}
}
catch(LineUnavailableExceptione)
{
if(DEBUG){e.printStackTrace();}
}
catch(Exceptione)
{
if(DEBUG){e.printStackTrace();}
}
if(DEBUG){out("AudioCommon.getTargetDataLine():returning
line:"+targetDataLine);}
returntargetDataLine;
}
/**ChecksiftheencodingisPCM.
*/
publicstaticbooleanisPcm(AudioFormat.Encodingencoding)
{
returnencoding.equals(AudioFormat.Encoding.PCM_SIGNED)
||encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED);
}
/**TODO:
*/
privatestaticvoidout(StringstrMessage)
{
System.out.println(strMessage);
}
/***AudioCommon.java***/
packagebr.ufsc.inf.lagar.verify.animated1.osc;
/*
*AudioPlayer.java
*
*Thisfileispartofjsresources.org
*/
/*
*Copyright(c)1999,2000byMatthiasPfisterer
*Allrightsreserved.
*
*Redistributionanduseinsourceandbinaryforms,withorwithout
*modification,arepermittedprovidedthatthefollowingconditions
*aremet:
*
*Redistributionsofsourcecodemustretaintheabovecopyrightnotice,
*thislistofconditionsandthefollowingdisclaimer.
*Redistributionsinbinaryformmustreproducetheabovecopyright
*notice,thislistofconditionsandthefollowingdisclaimerinthe
*documentationand/orothermaterialsprovidedwiththedistribution.
*
93
*THISSOFTWAREISPROVIDEDBYTHECOPYRIGHTHOLDERSANDCONTRIBUTORS
*"ASIS"ANDANYEXPRESSORIMPLIEDWARRANTIES,INCLUDING,BUTNOT
*LIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESS
*FORAPARTICULARPURPOSEAREDISCLAIMED.INNOEVENTSHALLTHE
*COPYRIGHTOWNERORCONTRIBUTORSBELIABLEFORANYDIRECT,INDIRECT,
*INCIDENTAL,SPECIAL,EXEMPLARY,ORCONSEQUENTIALDAMAGES
*(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENTOFSUBSTITUTEGOODSOR
*SERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION)
*HOWEVERCAUSEDANDONANYTHEORYOFLIABILITY,WHETHERINCONTRACT,
*STRICTLIABILITY,ORTORT(INCLUDINGNEGLIGENCEOROTHERWISE)
*ARISINGINANYWAYOUTOFTHEUSEOFTHISSOFTWARE,EVENIFADVISED
*OFTHEPOSSIBILITYOFSUCHDAMAGE.
*/
/*
|<thiscodeisformattedtofitinto80columns>|
*/
importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.InputStream;
importjava.io.IOException;
importjava.net.URL;
importjavax.sound.sampled.AudioFormat;
importjavax.sound.sampled.AudioInputStream;
importjavax.sound.sampled.AudioSystem;
importjavax.sound.sampled.DataLine;
importjavax.sound.sampled.LineUnavailableException;
importjavax.sound.sampled.Mixer;
importjavax.sound.sampled.SourceDataLine;
/*Ifthecompilationfailsbecausethisclassisnotavailable,
getgnu.getoptfromtheURLgiveninthecommentbelow.
*/
//importgnu.getopt.Getopt;
/**<titleabbrev>AudioPlayer</titleabbrev>
<title>Playinganaudiofile(advanced)</title>
<formalpara><title>Purpose</title>
<para>
Playsasingleaudiofile.Capableofplayingsome
compressedaudioformats(Alaw,μlaw,maybeoggvorbis,mp3,
GSM06.10).
Allowscontroloverbuffering
andwhichmixertouse.
</para></formalpara>
<formalpara><title>Usage</title>
<para>
<cmdsynopsis>
<command>javaAudioPlayer</command>
<argchoice="plain"><option>l</option></arg>
</cmdsynopsis>
<cmdsynopsis>
<command>javaAudioPlayer</command>
<arg><option>M<replaceable>mixername</replaceable></option></arg>
<arg><option>e<replaceable>buffersize</replaceable></option></arg>
<arg><option>i<replaceable>buffersize</replaceable></option></arg>
94
<argchoice="plain"><replaceable>audiofile</replaceable></arg>
</cmdsynopsis>
</para></formalpara>
<formalpara><title>Parameters</title>
<variablelist>
<varlistentry>
<term><option>h</option></term>
<listitem><para>printusagemessage</para></listitem>
</varlistentry>
<varlistentry>
<term><option>l</option></term>
<listitem><para>liststheavailablemixers</para></listitem>
</varlistentry>
<varlistentry>
<term><option>M<replaceable>mixername</replaceable></option></term>
<listitem><para>selectsamixertoplayon</para></listitem>
</varlistentry>
<varlistentry>
<term><option>e<replaceable>buffersize</replaceable></option></term>
<listitem><para>thebuffersizetouseintheapplication
("extern")</para></listitem>
</varlistentry>
<varlistentry>
<term><option>i<replaceable>buffersize</replaceable></option></term>
<listitem><para>thebuffersizetouseinJavaSound
("intern")</para></listitem>
</varlistentry>
<varlistentry>
<term><option>E<replaceable>endianess</replaceable></option></term>
<listitem><para>theendianess("big"or"little")touseinconversions.The
defaultislittle.Specifyingthisoptionforcesaconversion,eveniftheaudio
formatissupportedbySourceDataLinesdirectly.</para></listitem>
</varlistentry>
<varlistentry>
<term><option>S<replaceable>samplesize</replaceable></option></term>
<listitem><para>thesamplesizeinbitstouseinconversions.Thedefault
is16.Specifyingthisoptionforcesaconversion,eveniftheaudioformatis
supportedbySourceDataLinesdirectly.</para></listitem>
</varlistentry>
<varlistentry>
<term><option>D</option></term>
<listitem><para>enabledebuggingoutput</para></listitem>
</varlistentry>
<varlistentry>
<term><option>f</option></term>
<listitem><para>interpretfilenameargumentsasfilenames.Thisisthe
default.Thisoptionisexclusiveto<option>u</option>.</para></listitem>
</varlistentry>
<varlistentry>
<term><option>u</option></term>
<listitem><para>interpretfilenameargumentsasURLs.Thedefaultisto
interpretthemasfilenames.Thisoptionisexclusiveto<option>
f</option>.</para></listitem>
</varlistentry>
<varlistentry>
<term><option><replaceable>audiofile</replaceable></option></term>
<listitem><para>thefilenameoftheaudiofiletoplay</para></listitem>
</varlistentry>
</variablelist>
</formalpara>
<formalpara><title>Bugs,limitations</title>
95
<para>
Compressedformatscanbehandleddependingonthe
capabilitiesoftheJavaSoundimplementation.
AlawandμlawcanbehandledinanyknownJavaSoundimplementation.
Oggvorbis,mp3andGSM06.10canbehandledbyTritonus.Ifyouwanttoplay
these
formatswiththeSunjdk1.3/1.4,youhavetoinstalltherespectiveplugins
from<ulinkurl
="http://www.tritonus.org/plugins.html">TritonusPlugins</ulink>.
</para>
</formalpara>
<formalpara><title>Sourcecode</title>
<para>
<ulinkurl="AudioPlayer.java.html">AudioPlayer.java</ulink>,
<ulinkurl="AudioLoop.java.html">AudioLoop.java</ulink>,
<olinktargetdocent="getopt">gnu.getopt.Getopt</olink>
</para>
</formalpara>
*/
publicclassAudioPlayer
{
/**Flagfordebuggingmessages.
*Iftrue,somemessagesaredumpedtotheconsole
*duringoperation.
*/
privatestaticbooleanDEBUG=false;
privatestaticintDEFAULT_EXTERNAL_BUFFER_SIZE=128000;
publicstaticvoidmain(InputStreaminputStream)
throwsException
{
/**DeterminesifcommandlineargumentsareinteretedasURL.
Iftrue,filenameargumentsonthecommandlineare
interpretedasURL.Iffalse,theyareinterpretedas
filenames.Thisflagissetbythecommandline
option"u".Itisresetbythecommandlineoption
"f".
*/
booleanbInterpretFilenameAsUrl=false;
/**Flagforforcingaconversion.
Ifsettotrue,aconversionoftheAudioInputStream
(AudioSystem.getAudioInputStream(...,AudioInputStream))
isdoneeveniftheformatoftheoriginalAudioInputStream
wouldbesupportedforSourceDataLinesdirectly.This
flagissetbythecommandlineoptions"E"and"S".
*/
booleanbForceConversion=false;
/**Endianessvaluetouseinconversion.
IfaconversionoftheAudioInputStreamisdone,
thisvaluesisusedasendianessinthetargetAudioFormat.
Thedefaultvaluecanbealteredbythecommandline
option"B".
*/
booleanbBigEndian=false;
/**Samplesizevaluetouseinconversion.
96
IfaconversionoftheAudioInputStreamisdone,
thisvaluesisusedassamplesizeinthetarget
AudioFormat.
Thedefaultvaluecanbealteredbythecommandline
option"S".
*/
intnSampleSizeInBits=16;
StringstrMixerName=null;
intnExternalBufferSize=DEFAULT_EXTERNAL_BUFFER_SIZE;
intnInternalBufferSize=AudioSystem.NOT_SPECIFIED;
/*
*Parsingofcommandlineoptionstakesplace...
*/
//Getoptg=newGetopt("AudioPlayer",args,"hlufM:e:i:E:S:D");
//intc;
//while((c=g.getopt())!=1)
//{
//switch(c)
//{
//case'h':
//printUsageAndExit();
//
//case'l':
//AudioCommon.listMixersAndExit(true);
//
//case'u':
//bInterpretFilenameAsUrl=true;
//break;
//
//case'f':
//bInterpretFilenameAsUrl=false;
//break;
//
//case'M':
//strMixerName=g.getOptarg();
//if(DEBUG)out("AudioPlayer.main():mixername:"+
strMixerName);
//break;
//
//case'e':
//nExternalBufferSize=
Integer.parseInt(g.getOptarg());
//break;
//
//case'i':
//nInternalBufferSize=
Integer.parseInt(g.getOptarg());
//break;
//
//case'E':
//StringstrEndianess=g.getOptarg();
//strEndianess=strEndianess.toLowerCase();
//if(strEndianess.equals("big"))
//{
//bBigEndian=true;
//}
//elseif(strEndianess.equals("little"))
97
//{
//bBigEndian=false;
//}
//else
//{
//printUsageAndExit();
//}
//bForceConversion=true;
//break;
//
//case'S':
//nSampleSizeInBits=Integer.parseInt(g.getOptarg());
//bForceConversion=true;
//break;
//
//case'D':
//DEBUG=true;
//break;
//
//case'?':
//printUsageAndExit();
//
//default:
//out("getopt()returned"+c);
//break;
//}
//}
/*Wemakeshurethatthereisonlyonemoreargument,which
wetakeasthefilenameofthesoundfilewewanttoplay.*/
//StringstrFilenameOrUrl=null;
//for(inti=g.getOptind();i<args.length;i++)
//{
//if(strFilenameOrUrl==null)
//{
//strFilenameOrUrl=args[i];
//}
//else
//{
//printUsageAndExit();
//}
//}
//if(strFilenameOrUrl==null)
//{
//printUsageAndExit();
//}
AudioInputStreamaudioInputStream=null;
if(true||bInterpretFilenameAsUrl)
{
//URLurl=newURL(strFilenameOrUrl);
audioInputStream=
AudioSystem.getAudioInputStream(inputStream);
}
else
{
////Arewerequestedtousestandardinput?
//if(strFilenameOrUrl.equals(""))
//{
//InputStreaminputStream=new
BufferedInputStream(System.in);
//audioInputStream=
AudioSystem.getAudioInputStream(inputStream);
//}
98
//else
//{
//Filefile=newFile(strFilenameOrUrl);
//audioInputStream=
AudioSystem.getAudioInputStream(file);
//}
}
if(DEBUG)out("AudioPlayer.main():primaryAIS:"+
audioInputStream);
/*
*FromtheAudioInputStream,i.e.fromthesoundfile,
*wefetchinformationabouttheformatofthe
*audiodata.
*Theseinformationincludethesamplingfrequency,
*thenumberof
*channelsandthesizeofthesamples.
*Theseinformation
*areneededtoaskJavaSoundforasuitableoutputline
*forthisaudiostream.
*/
AudioFormataudioFormat=audioInputStream.getFormat();
if(DEBUG)out("AudioPlayer.main():primaryformat:"+audioFormat);
DataLine.Infoinfo=newDataLine.Info(SourceDataLine.class,
audioFormat,
nInternalBufferSize);
booleanbIsSupportedDirectly=AudioSystem.isLineSupported(info);
if(!bIsSupportedDirectly||bForceConversion)
{
AudioFormatsourceFormat=audioFormat;
AudioFormattargetFormat=newAudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.getSampleRate(),
nSampleSizeInBits,
sourceFormat.getChannels(),
sourceFormat.getChannels()*(nSampleSizeInBits/8),
sourceFormat.getSampleRate(),
bBigEndian);
if(DEBUG)
{
out("AudioPlayer.main():sourceformat:"+
sourceFormat);
out("AudioPlayer.main():targetformat:"+
targetFormat);
}
audioInputStream=
AudioSystem.getAudioInputStream(targetFormat,audioInputStream);
audioFormat=audioInputStream.getFormat();
if(DEBUG)out("AudioPlayer.main():convertedAIS:"+
audioInputStream);
if(DEBUG)out("AudioPlayer.main():convertedformat:"+
audioFormat);
}
SourceDataLineline=getSourceDataLine(strMixerName,audioFormat,
nInternalBufferSize);
if(line==null)
{
out("AudioPlayer:cannotgetSourceDataLineforformat"+
audioFormat);
System.exit(1);
}
if(DEBUG)out("AudioPlayer.main():line:"+line);
99
if(DEBUG)out("AudioPlayer.main():lineformat:"+
line.getFormat());
/*
*Stillnotenough.Thelinenowcanreceivedata,
*butwillnotpassthemontotheaudiooutputdevice
*(whichmeanstoyoursoundcard).Thishastobe
*activated.
*/
line.start();
/*
*Ok,finallythelineisprepared.Nowcomesthereal
*job:wehavetowritedatatotheline.Wedothis
*inaloop.First,wereaddatafromthe
*AudioInputStreamtoabuffer.Then,wewritefrom
*thisbuffertotheLine.Thisisdoneuntiltheend
*ofthefileisreached,whichisdetectedbya
*returnvalueof1fromthereadmethodofthe
*AudioInputStream.
*/
intnBytesRead=0;
byte[]abData=newbyte[nExternalBufferSize];
if(DEBUG)out("AudioPlayer.main():startingmainloop");
while(nBytesRead!=1)
{
try
{
nBytesRead=audioInputStream.read(abData,0,
abData.length);
}
catch(IOExceptione)
{
e.printStackTrace();
}
if(DEBUG)out("AudioPlayer.main():readfrom
AudioInputStream(bytes):"+nBytesRead);
if(nBytesRead>=0)
{
intnBytesWritten=line.write(abData,0,
nBytesRead);
if(DEBUG)out("AudioPlayer.main():writtento
SourceDataLine(bytes):"+nBytesWritten);
}
}
if(DEBUG)out("AudioPlayer.main():finishedmainloop");
/*
*Waituntilalldataisplayed.
*Thisisonlynecessarybecauseofthebugnotedbelow.
*(Ifwedonotwait,wewouldinterrupttheplaybackby
*prematurelyclosingthelineandexitingtheVM.)
*
*ThankstoMargieFitchforbringingmeontheright
*pathtothissolution.
*/
if(DEBUG)out("AudioPlayer.main():beforedrain");
line.drain();
/*
*Alldataareplayed.Wecanclosetheshop.
*/
100
if(DEBUG)out("AudioPlayer.main():beforeclose");
line.close();
///*
//*ThereisabugintheSunjdk1.3/1.4.
//*ItpreventscorrectterminationoftheVM.
//*Sowehavetoexitourselves.
//*ThisbughasbeenfixedfortheSunJDK1.5.0.
//*/
//if(DEBUG)
//{
//out("AudioPlayer.main():beforeexit");
//}
//System.exit(0);
}
//TODO:maybecanusedbyothers.AudioLoop?
//Inthiscase,movetoAudioCommon.
privatestaticSourceDataLinegetSourceDataLine(StringstrMixerName,
AudioFormataudioFormat,
intnBufferSize)
{
/*
*Askingforalineisarathertrickything.
*WehavetoconstructanInfoobjectthatspecifies
*thedesiredpropertiesfortheline.
*First,wehavetosaywhichkindoflinewewant.The
*possibilitiesare:SourceDataLine(forplayback),Clip
*(forrepeatedplayback)andTargetDataLine(for
*recording).
*Here,wewanttodonormalplayback,soweaskfor
*aSourceDataLine.
*Then,wehavetopassanAudioFormatobject,sothat
*theLineknowswhichformatthedatapassedtoit
*willhave.
*Furthermore,wecangiveJavaSoundahintabouthow
*bigtheinternalbufferforthelineshouldbe.This
*isn'tusedhere,signalingthatwe
*don'tcareabouttheexactsize.JavaSoundwilluse
*somedefaultvalueforthebuffersize.
*/
SourceDataLineline=null;
DataLine.Infoinfo=newDataLine.Info(SourceDataLine.class,
audioFormat,nBufferSize);
try
{
if(strMixerName!=null)
{
Mixer.InfomixerInfo=
AudioCommon.getMixerInfo(strMixerName);
if(mixerInfo==null)
{
out("AudioPlayer:mixernotfound:"+
strMixerName);
System.exit(1);
}
Mixermixer=AudioSystem.getMixer(mixerInfo);
line=(SourceDataLine)mixer.getLine(info);
}
else
{
line=(SourceDataLine)AudioSystem.getLine(info);
}
101
/*
*Thelineisthere,butitisnotyetreadyto
*receiveaudiodata.Wehavetoopentheline.
*/
line.open(audioFormat,nBufferSize);
}
catch(LineUnavailableExceptione)
{
if(DEBUG)e.printStackTrace();
}
catch(Exceptione)
{
if(DEBUG)e.printStackTrace();
}
returnline;
}
privatestaticvoidprintUsageAndExit()
{
out("AudioPlayer:usage:");
out("\tjavaAudioPlayerh");
out("\tjavaAudioPlayerl");
out("\tjavaAudioPlayer");
out("\t\t[M<mixername>]");
out("\t\t[e<externalBuffersize>]");
out("\t\t[i<internalBuffersize>]");
out("\t\t[S<SampleSizeInBits>]");
out("\t\t[B(big|little)]");
out("\t\t[D]");
out("\t\t[u|f]");
out("\t\t<soundfileOrUrl>");
System.exit(1);
}
privatestaticvoidout(StringstrMessage)
{
System.out.println(strMessage);
}
}
/***AudioPlayer.java***/
/*
*BallFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
102
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
importbr.ufsc.inf.lagar.filter.Filterable;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.util.Arrays;
publicclassBallFilterextendsAbstractGameFilter{
int[]inputBalls;
/**CreatesanewinstanceofBallFilter*/
publicBallFilter(){
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
String[]params=input.split(Filterable.OR_SEPARATOR);
this.inputBalls=newint[params.length];
for(inti=0;i<params.length;++i){
Strings=params[i];
try{
this.inputBalls[i]=Integer.parseInt(s.trim());
}
catch(NumberFormatExceptionnfex){
thrownewTextInputFilterException(nfex);
}
Arrays.sort(this.inputBalls);
publicStringgetShortName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Ball_filter");
}
publicStringgetFullName(){
returngetShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Ball_filter_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Ball_filter_help");
103
}
publicbooleanfilter(GameCardcard){
byte[]balls=card.getBalls();
for(intb:balls){
if(Arrays.binarySearch(this.inputBalls,b)>=0){
returnthis.isMode();
}
}
return!this.isMode();
}
}
/*
*BallFrequencyAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.DefaultTableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Color;
importjava.util.ArrayList;
importjava.util.List;
publicclassBallFrequencyAnalysisextendsDefaultTableChartAnalysis{
/**CreatesanewinstanceofBallFrequencyAnalysis*/
publicBallFrequencyAnalysis(){
}
protectedvoidfillTableChart(){
GameCardcardBuffer=newGameCard();
for(intindex=0;this.gci.hasNext();++index){
this.gci.next(cardBuffer);
byte[]balls=cardBuffer.getBalls();
for(inti=0;i<balls.length;++i){
intball=balls[i];
Stringcategory=String.valueOf(ball);
104
this.tcols.get(category)[index]=this.hit;
Integerdc=this.dataChart.get(category);
this.dataChart.put(category,++dc);
}
this.tcols.get(this.columnOne)[index]=new
CellData(String.valueOf(cardBuffer.getSerial()),null,Color.BLACK,false);
}
}
protectedList<String>buildCategories(){
List<String>result=newArrayList<String>();
intmaxNum=getCurrentGameConfiguration().getNumbersPerCard();
for(inti=1;i<=maxNum;++i){
result.add(String.valueOf(i));
}
returnresult;
}
publicStringgetName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Ball_frequency_analysis");
}
publicStringgetHelpInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Ball_frequency_analysis_help_info");
}
}
/*
*Ball.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.utils;
importbr.ufsc.inf.lagar.main.GameManager;
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
105
publicclassBallextendsJButtonimplementsActionListener{
privateintnumber;
privatebooleanstate;
publicstaticintcountNumbers=0;
privateintmaxBalls;
publicBall(intnumber,KeyListenerk){
this.setPreferredSize(newDimension(15,15));
this.addKeyListener(k);
//this.resetKeyboardActions();
//this.setFocusPainted(false);
this.setBorder(null);
this.setBackground(Color.white);
this.addActionListener(this);
this.number=number;
this.state=false;
this.setText(String.valueOf(number));
this.maxBalls=GameManager.getCurrentGame().getNumbersPerCard();
/**
*Getterforpropertystate.
*
*@returnValueofpropertystate.
*/
publicbooleanisState(){
returnstate;
}
publicvoidrestart(){
this.state=false;
this.setBackground(Color.white);
publicvoidblue(){
this.setBackground(Color.blue);
publicvoidred(){
this.setBackground(Color.red);
/**
*Setterforpropertystate.
*
*@paramstateNewvalueofpropertystate.
106
*/
publicvoidbtClick(){
if(Ball.countNumbers<this.maxBalls||this.state){
if(this.state){
this.setBackground(Color.white);
this.state=false;
Ball.countNumbers;
}
else{
this.setBackground(Color.green);
this.state=true;
Ball.countNumbers++;
}
/**
*Getterforpropertynumber.
*
*@returnValueofpropertynumber.
*/
publicintgetNumber(){
returnnumber;
}
publicvoidactionPerformed(java.awt.event.ActionEventactionEvent){
this.btClick();
}//Button/*
*BallMatrixPanel.java
*
*Createdon18deAbrilde2007,21:33
*/
packagebr.ufsc.inf.lagar.utils;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.awt.GridLayout;
/**
*
*@authorlagar
*/
publicclassBallMatrixPanelextendsjavax.swing.JPanel{
privateBall[]matrix;
/**CreatesnewformBallMatrixPanel*/
publicBallMatrixPanel(){
initComponents();
}
publicvoidinitMatrix(intnums,introws,intcols){
107
GridLayoutgl=(GridLayout)this.getLayout();
gl.setColumns(cols);
gl.setRows(rows);
gl.setHgap(4);
gl.setVgap(3);
this.inicializaMatriz();
}
privatevoidinicializaMatriz(){
intbs=GameManager.getCurrentGame().getNumbersPerCard();
this.matrix=newBall[bs+1];
for(inti=1;i<this.getMatrix().length;i++){
this.getMatrix()[i]=newBall(i,this.getKeyListeners()[0]);
this.add(this.getMatrix()[i]);
publicBall[]getMatrix(){
returnmatrix;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
setLayout(newjava.awt.GridLayout());
addKeyListener(newjava.awt.event.KeyAdapter(){
publicvoidkeyPressed(java.awt.event.KeyEventevt){
formKeyPressed(evt);
}
});
}//</editorfold>//GENEND:initComponents
privatevoidformKeyPressed(java.awt.event.KeyEventevt){//GEN
FIRST:event_formKeyPressed
//TODOaddyourhandlingcodehere:
}//GENLAST:event_formKeyPressed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
//Endofvariablesdeclaration//GENEND:variables
}
/*
*Beeps.java
*
*Createdon4deNovembrode2004,02:11
*/
/**
108
*
*@authorlagar
*/
packagebr.ufsc.inf.lagar.verify.animated1;
importbr.ufsc.inf.lagar.verify.animated1.osc.AudioPlayer;
importjava.io.*;
importjava.net.*;
publicclassBeeps{
byte[]beep;
byte[]goodBeep;
byte[]badBeep;
byte[]greatBeep;
/**CreatesanewinstanceofBeeps*/
publicBeeps()throwsIOException{
InputStreamis=getClass().getResourceAsStream("/resources/snd/miss.au");
ByteArrayOutputStreambos=newByteArrayOutputStream();
byte[]buf=newbyte[8192];
intn=0;
while((n=is.read(buf))!=1){
bos.write(buf,0,n);
}
this.beep=bos.toByteArray();
is=getClass().getResourceAsStream("/resources/snd/match.au");
bos=newByteArrayOutputStream();
n=0;
while((n=is.read(buf))!=1){
bos.write(buf,0,n);
}
this.goodBeep=bos.toByteArray();
is=getClass().getResourceAsStream("/resources/snd/win2.au");
bos=newByteArrayOutputStream();
n=0;
while((n=is.read(buf))!=1){
bos.write(buf,0,n);
}
this.greatBeep=bos.toByteArray();
publicvoidbeep(){
ByteArrayInputStreamb=newByteArrayInputStream(this.beep);
try{
AudioPlayer.main(b);
}catch(Exceptionex){
ex.printStackTrace();
}
}
publicvoidgoodBeep(){
109
ByteArrayInputStreamb=newByteArrayInputStream(this.goodBeep);
try{
AudioPlayer.main(b);
}catch(Exceptionex){
ex.printStackTrace();
}
publicvoidgreatBeep(){
ByteArrayInputStreamb=newByteArrayInputStream(this.greatBeep);
try{
AudioPlayer.main(b);
}catch(Exceptionex){
ex.printStackTrace();
}
publicvoidbadBeep(){
}
/*
*CaixaLoader.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.resultloader;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.util.List;
importjava.util.zip.ZipEntry;
110
importjava.util.zip.ZipInputStream;
publicabstractclassCaixaLoaderimplementsResultLoader{
protectedURLresultPath;
protectedInputStreamgetHtmlStream()throwsIOException{
if(this.resultPath.getProtocol().equalsIgnoreCase("http")||
this.resultPath.getProtocol().equalsIgnoreCase("ftp")){
InputStreamin=this.resultPath.openStream();
byte[]buf=newbyte[8192];
StringlocalPath=LagarLotteryGlobals.LL_HOME;
intpos=this.resultPath.getPath().lastIndexOf("/");
localPath=localPath+this.resultPath.getPath().substring(pos);
FilelocalFile=newFile(localPath);
if(!localFile.exists()){
localFile.createNewFile();
}
BufferedOutputStreambout=newBufferedOutputStream(new
FileOutputStream(localPath));
intread=0;
while((read=in.read(buf))!=1){
bout.write(buf,0,read);
}
bout.flush();
bout.close();
in.close();
this.resultPath=localFile.toURI().toURL();
ZipInputStreamin=newZipInputStream(new
BufferedInputStream(this.resultPath.openStream()));
ZipEntryentry=in.getNextEntry();
if(entry==null)thrownewIllegalArgumentException("BADZIP");
while(!entry.getName().contains("HTM")){
entry=in.getNextEntry();
if(entry==null)thrownewIllegalArgumentException("BADZIP");
}
returnin;
}
publicvoidsetResultPath(Stringurl)throwsMalformedURLException{
this.resultPath=getClass().getResource(url);
if(this.resultPath==null){
this.resultPath=newURL(url);
}
}
publicStringgetResultPath(){
returnthis.resultPath.toString();
}
111
}
/*
*CardReaderWriterTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.zmisc.test;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.generator.GeneratorHeader;
importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipInputStream;
publicclassCardReaderWriterTest{
/**CreatesanewinstanceofCardReaderWriterTest*/
publicCardReaderWriterTest(){
}
publicvoidreadCards()throwsException{
FileInputStreamfin=newFileInputStream("/home/lagar/teste/bb.llg");
ZipInputStreamzin=newZipInputStream(fin);
ZipEntrye=null;
while((e=zin.getNextEntry())!=null){
if(e.getName().equals(LagarLotteryGlobals.GENERATED_HEADER_NAME)){
break;
}
}
GeneratorHeaderheader=GeneratorHeader.loadFromStream(zin);
zin.closeEntry();
zin.close();
publicvoidtestGenCardIO()throwsIOException{
112
Filef=newFile("/home/lagar/teste/bb.llg");
GenCardIOio=newGenCardIO(f);
GameCardbuff=newGameCard(0,null,io.getBallsPerCard());
io.skipToCard(buff,io.size());
System.out.println(buff);
}
publicstaticvoidmain(String[]args)throwsException{
newCardReaderWriterTest().testGenCardIO();
}
}
/*
*CellData.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importjava.awt.Color;
publicclassCellData{
privateStringtext;
privateColorbgColor;
privateColorfgColor;
privatebooleanhit;
publicCellData(){
publicCellData(Stringtext,Colorbg,Colorfg,booleanhit){
this.text=text;
this.bgColor=bg;
this.setFgColor(fg);
this.setHit(hit);
}
publicStringgetText(){
returntext;
113
}
publicvoidsetText(Stringtext){
this.text=text;
}
publicColorgetBgColor(){
returnbgColor;
}
publicvoidsetBgColor(Colorc){
this.bgColor=c;
}
publicbooleanisHit(){
returnhit;
}
publicvoidsetHit(booleanhit){
this.hit=hit;
}
publicColorgetFgColor(){
returnfgColor;
}
publicvoidsetFgColor(ColorfgColor){
this.fgColor=fgColor;
}
}
/*
*CellDataRenderer.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importjava.awt.Color;
importjava.awt.Component;
importjavax.swing.JButton;
importjavax.swing.JLabel;
importjavax.swing.JTable;
importjavax.swing.SwingConstants;
importjavax.swing.border.Border;
importjavax.swing.table.TableCellRenderer;
114
publicclassCellDataRendererextendsJLabelimplementsTableCellRenderer{
privatestaticColorDEFAULT_COLOR=newJButton("a").getBackground();
publicCellDataRenderer(){
this.setOpaque(true);
this.setHorizontalAlignment(SwingConstants.CENTER);
}
publicComponentgetTableCellRendererComponent(JTabletable,Objectvalue,
booleanisSelected,booleanhasFocus,introw,intcolumn){
CellDatac=(CellData)value;
ColorbgColor=c.getBgColor();
ColorfgColor=c.getFgColor();
if(bgColor==null)bgColor=DEFAULT_COLOR;
if(!isSelected){
this.setBackground(bgColor);
}
else{
this.setBackground(bgColor.darker());
}
this.setText(c.getText());
this.setForeground(fgColor);
returnthis;
}
}
/*
*Chartable.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importorg.jfree.chart.JFreeChart;
/**
*
*@authorlagar
*/
publicinterfaceChartable{
publicJFreeChartgetChart();
115
}
/*
*ChartAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importjava.awt.CardLayout;
importjava.util.ArrayList;
importjava.util.List;
importjavax.swing.JPanel;
importorg.jfree.chart.ChartPanel;
publicabstractclassChartAnalysisextendsAnalysisimplementsChartable{
publicList<JPanel>getPanels(){
List<JPanel>panels=newArrayList<JPanel>();
ChartPanelpanel=newChartPanel(getChart());
panel.setLayout(newCardLayout());
panel.setName("Chart");
panels.add(panel);
returnpanels;
}
}
/*
*LineAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
116
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.DefaultTableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Color;
importjava.lang.reflect.InvocationTargetException;
importjava.text.DecimalFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjavax.swing.JOptionPane;
importjavax.swing.SwingUtilities;
importorg.jfree.chart.ChartFactory;
importorg.jfree.chart.JFreeChart;
importorg.jfree.chart.labels.PieSectionLabelGenerator;
importorg.jfree.chart.labels.StandardPieSectionLabelGenerator;
importorg.jfree.chart.plot.MultiplePiePlot;
importorg.jfree.chart.plot.PiePlot;
importorg.jfree.data.category.DefaultCategoryDataset;
importorg.jfree.data.general.DefaultPieDataset;
importorg.jfree.util.TableOrder;
publicclassColumnAnalysisextendsDefaultTableChartAnalysis{
privateint[][]colsData;
/**CreatesanewinstanceofLineAnalysis*/
publicColumnAnalysis(){
}
protectedvoidfillTableChart(){
GameCardcardBuffer=newGameCard();
intperLine=getCurrentGameConfiguration().getNumbersPerLine();
inttotal=getCurrentGameConfiguration().getNumbersPerCard();
intnumCols=perLine;
intsizeCols=total/perLine;
int[]sum=newint[numCols+1];
for(intindex=0;this.gci.hasNext();++index){
this.gci.next(cardBuffer);
byte[]balls=cardBuffer.getBalls();
for(inti=0;i<balls.length;++i){
intball=balls[i];
for(intk=1;k<=numCols;++k){
int[]col=this.colsData[k];
if(Arrays.binarySearch(col,ball)>=0){
++sum[k];
break;
}
}
}
117
for(inti=1;i<=numCols;++i){
Stringcategory=String.valueOf(i);
this.tcols.get(category)[index]=this.getHitz(sum[i]);
Integerdc=this.dataChart.get(category);
this.dataChart.put(category,dc+sum[i]);
}
this.tcols.get(this.columnOne)[index]=new
CellData(String.valueOf(cardBuffer.getSerial()),null,Color.BLACK,false);
Arrays.fill(sum,0);
}
protectedList<String>buildCategories(){
List<String>result=newArrayList<String>();
intperLine=getCurrentGameConfiguration().getNumbersPerLine();
inttotal=getCurrentGameConfiguration().getNumbersPerCard();
intnumCols=perLine;
intsizeCols=total/perLine;
for(inti=1;i<=numCols;++i){
result.add(String.valueOf(i));
this.colsData=newint[numCols+1][perLine];
}
for(inti=1;i<=numCols;++i){
intcurrNum=i;
for(intj=0;j<sizeCols;++j){
this.colsData[i][j]=currNum;
currNum+=perLine;
}
returnresult;
}
publicStringgetName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Column_analysis");
}
publicStringgetHelpInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Column_analysis_help_info");
}
}
/**
*CombinationGenerator.java
*
*CombinationGenerator
118
*byMichaelGilleland,MerriamParkSoftware
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.generator;
//
//Systematicallygeneratecombinations.
//
importjava.math.BigInteger;
publicclassCombinationGenerator
{
privateint[]a;
privateintn;
privateintr;
privateBigIntegernumLeft;
privateBigIntegertotal;
//
//Constructor
//
publicCombinationGenerator(intn,intr)
{
if(r>n)
{
thrownewIllegalArgumentException();
}
if(n<1)
{
thrownewIllegalArgumentException();
}
this.n=n;
this.r=r;
a=newint[r];
BigIntegernFact=getFactorial(n);
BigIntegerrFact=getFactorial(r);
BigIntegernminusrFact=getFactorial(nr);
total=nFact.divide(rFact.multiply(nminusrFact));
reset();
}
//
//Reset
//
119
publicvoidreset()
{
for(inti=0;i<a.length;i++)
{
a[i]=i;
}
numLeft=newBigInteger(total.toString());
}
//
//Returnnumberofcombinationsnotyetgenerated
//
publicBigIntegergetNumLeft()
{
returnnumLeft;
}
//
//Aretheremorecombinations?
//
publicbooleanhasMore()
{
returnnumLeft.compareTo(BigInteger.ZERO)==1;
}
//
//Returntotalnumberofcombinations
//
publicBigIntegergetTotal()
{
returntotal;
}
//
//Computefactorial
//
publicstaticBigIntegergetFactorial(intn)
{
BigIntegerfact=BigInteger.ONE;
for(inti=n;i>1;i)
{
fact=fact.multiply(newBigInteger(Integer.toString(i)));
}
returnfact;
}
//
//Generatenextcombination(algorithmfromRosenp.286)
//
publicint[]getNext()
{
if(numLeft.equals(total))
{
numLeft=numLeft.subtract(BigInteger.ONE);
returna;
}
inti=r1;
120
while(a[i]==nr+i)
{
i;
}
a[i]=a[i]+1;
for(intj=i+1;j<r;j++)
{
a[j]=a[i]+ji;
}
numLeft=numLeft.subtract(BigInteger.ONE);
returna;
}
}/**
*CombinationGeneratorTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.utils;
importbr.ufsc.inf.lagar.generator.CombinationGenerator;
importjunit.framework.TestCase;
/**
*@authorlagar
*
*/
publicclassCombinationGeneratorTestextendsTestCase
{
publicvoidtestCombinationGenerator()
{
int[]elements={10,20,30,40,50};
int[]indices;
CombinationGeneratorx=newCombinationGenerator(elements.length,3);
StringBuffercombination=newStringBuffer();
while(x.hasMore())
{
indices=x.getNext();
for(inti=0;i<indices.length;i++)
{
combination.append(elements[indices[i]]);
if(indices.lengthi!=1)
combination.append("");
}
121
combination.append("\n");
}
StringBufferexpectedValue=newStringBuffer();
expectedValue.append("102030");
expectedValue.append("\n");
expectedValue.append("102040");
expectedValue.append("\n");
expectedValue.append("102050");
expectedValue.append("\n");
expectedValue.append("103040");
expectedValue.append("\n");
expectedValue.append("103050");
expectedValue.append("\n");
expectedValue.append("104050");
expectedValue.append("\n");
expectedValue.append("203040");
expectedValue.append("\n");
expectedValue.append("203050");
expectedValue.append("\n");
expectedValue.append("204050");
expectedValue.append("\n");
expectedValue.append("304050");
expectedValue.append("\n");
System.out.println(combination.toString());
assertEquals("CombinationGeneratorTest",combination.toString(),
expectedValue.toString());
}
}
/*
*DecisionDialog.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui.dialog;
/**
*
*@authorlagar
*/
publicclassDecisionDialogextendsjavax.swing.JDialog{
/**CreatesnewformDecisionDialog*/
publicDecisionDialog(java.awt.Frameparent,booleanmodal){
122
super(parent,modal);
initComponents();
this.setLocationRelativeTo(null);
}
publicbr.inf.ufsc.lagar.swingutil.SimpleInternalFramegetTitlePanel(){
returntitlePanel;
}
publicjavax.swing.JButtongetCancelButton(){
returncancelButton;
}
publicjavax.swing.JPanelgetMainPanel(){
returnmainPanel;
}
publicjavax.swing.JButtongetOkButton(){
returnokButton;
}
publicjavax.swing.JPanelgetButtonsPanel(){
returnbuttonsPanel;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
titlePanel=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
mainPanel=newjavax.swing.JPanel();
buttonsPanel=newjavax.swing.JPanel();
cancelButton=newjavax.swing.JButton();
okButton=newjavax.swing.JButton();
jSeparator1=newjavax.swing.JSeparator();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
setTitle(bundle.getString("Option"));//NOI18N
titlePanel.setTitle("Title");
mainPanel.setLayout(newjava.awt.CardLayout());
cancelButton.setText(bundle.getString("Cancel"));//NOI18N
okButton.setText(bundle.getString("Ok"));//NOI18N
org.jdesktop.layout.GroupLayoutbuttonsPanelLayout=new
org.jdesktop.layout.GroupLayout(buttonsPanel);
buttonsPanel.setLayout(buttonsPanelLayout);
buttonsPanelLayout.setHorizontalGroup(
buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
buttonsPanelLayout.createSequentialGroup()
.addContainerGap(343,Short.MAX_VALUE)
123
.add(okButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cancelButton)
.addContainerGap())
);
buttonsPanelLayout.linkSize(newjava.awt.Component[]{cancelButton,
okButton},org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonsPanelLayout.setVerticalGroup(
buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(buttonsPanelLayout.createSequentialGroup()
.add(buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.Group
Layout.BASELINE)
.add(cancelButton)
.add(okButton))
.addContainerGap(12,Short.MAX_VALUE))
);
buttonsPanelLayout.linkSize(newjava.awt.Component[]{cancelButton,
okButton},org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(titlePanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,511,
Short.MAX_VALUE)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,511,
Short.MAX_VALUE)
.add(buttonsPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(jSeparator1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,511,
Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(titlePanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,233,
Short.MAX_VALUE)
.add(2,2,2)
.add(jSeparator1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,10,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonsPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
pack();
}//</editorfold>//GENEND:initComponents
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JPanelbuttonsPanel;
privatejavax.swing.JButtoncancelButton;
privatejavax.swing.JSeparatorjSeparator1;
privatejavax.swing.JPanelmainPanel;
124
privatejavax.swing.JButtonokButton;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFrametitlePanel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*DefaultGameCardPrinter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.printer;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameCardLayout;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.Point;
importjava.awt.print.PageFormat;
importjava.awt.print.Paper;
importjava.awt.print.PrinterException;
importjava.io.File;
importjava.io.IOException;
importjava.util.List;
publicclassDefaultGameCardPrinterextendsGameCardPrinter{
privateGenCardIOcards;
privateGameCardcardBuffer=newGameCard();
/**CreatesanewinstanceofDefaultGameCardPrinter*/
publicDefaultGameCardPrinter(){
}
publicvoidsetFile(FilegameCard)throwsIOException{
this.cards=newGenCardIO(gameCard);
}
publicintprint(Graphicsg,PageFormatpf,intpageIndex)throws
PrinterException{
if(cards.size()<(pageIndex+1)){
returnNO_SUCH_PAGE;
125
}
try{
this.cards.skipToCard(cardBuffer,pageIndex+1);
}catch(IOExceptionex){
thrownewRuntimeException(ex);
}
this.printCard(this.cardBuffer,g,pf);
this.printExtendedBalls(this.cardBuffer,g,pf,pageIndex);
this.printExtendedText(this.cardBuffer,g,pf,pageIndex);
returnPAGE_EXISTS;
}
privatevoidprintCard(GameCardgc,Graphicsg,PageFormatpf){
/*User(0,0)istypicallyoutsidetheimageablearea,sowemust
*translatebytheXandYvaluesinthePageFormattoavoidclipping
*/
Graphics2Dg2d=(Graphics2D)g;
Paperp=(Paper)pf.getPaper().clone();
p.setImageableArea(0,0,p.getWidth(),p.getHeight());
pf.setPaper(p);
doublex=(pf.getWidth()/2)cmToPixel(4.1);
doubley=0;
g2d.translate(x,y);
GameCardLayoutgcl=GameManager.getCurrentGame().getCardLayout();
doublewidth=gcl.getBallWidth();
doubleheight=gcl.getBallHeigth();
for(inti:gc.getBalls()){
Point.Doublep2d=gcl.getBalls().get(i);
/*Nowweperformourrendering*/
g2d.fillRect((int)cmToPixel(p2d.x),(int)cmToPixel(p2d.y),
(int)cmToPixel(width),(int)cmToPixel(height));
}
protectedvoidprintExtendedText(GameCardgc,Graphicsg,PageFormatpf,int
pageIndex)throwsPrinterException{
GameCardLayoutgcl=GameManager.getCurrentGame().getCardLayout();
GameCardLayout.ExtendedTextext=gcl.getExtendedText();
doublex=(ext.getX());
doubley=(ext.getY());
Graphics2Dg2d=(Graphics2D)g;
g2d.drawString("#"+gc.getSerial(),(int)cmToPixel(x),(int)cmToPixel(y));
}
protectedvoidprintExtendedBalls(GameCardgc,Graphicsg,PageFormatpf,int
pageIndex)throwsPrinterException{
126
/*
*DefaultTableChartAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importbr.ufsc.inf.lagar.main.GameCardIterator;
importjava.awt.Color;
importjava.text.DecimalFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.LinkedHashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importorg.jfree.chart.ChartFactory;
importorg.jfree.chart.JFreeChart;
importorg.jfree.chart.labels.PieSectionLabelGenerator;
importorg.jfree.chart.labels.StandardPieSectionLabelGenerator;
importorg.jfree.chart.plot.PiePlot;
importorg.jfree.data.general.DefaultPieDataset;
publicabstractclassDefaultTableChartAnalysisextendsTableChartAnalysis{
protectedGameCardIteratorgci;
protectedList<String>columns;
protectedMap<String,CellData[]>tcols;
protectedMap<String,Integer>dataChart;
protectedStringcolumnOne="n";
protectedCellDatahit=newCellData("x",newColor(40,210,20),Color.BLACK,
true);
protectedCellDatamiss=newCellData("",newColor(255,255,255),Color.BLACK,
false);
privateMap<Integer,CellData>misses=newHashMap<Integer,CellData>();
privateMap<Integer,CellData>hitz=newHashMap<Integer,CellData>();
/**CreatesanewinstanceofDefaultTableChartAnalysis*/
publicDefaultTableChartAnalysis(){
}
publicintgetRowCount(){
return(int)this.gci.size();
127
}
publicintgetColumnCount(){
returnthis.columns.size();
}
publicStringgetColumnName(intcolumnIndex){
returnthis.columns.get(columnIndex);
}
publicCellDatagetCellDataAt(introwIndex,intcolumnIndex){
Stringcat=this.columns.get(columnIndex);
CellData[]rows=this.tcols.get(cat);
CellDatacd=rows[rowIndex];
//if(!cd.isHit()&&columnIndex!=0&&cd.getText().equals("")){
//
//if(rowIndex==0){
//rows[rowIndex]=this.getMiss(1);
//returnrows[rowIndex];
//}
////CellDataup=this.getCellDataAt(rowIndex1,columnIndex);
//CellDataup=this.tcols.get(cat)[rowIndex1];
//if(up.isHit()){
//rows[rowIndex]=this.getMiss(1);
//returnrows[rowIndex];
//}
////if(up.getText()==null||up.getText().equals("")){
////up=this.getCellDataAt(rowIndex,columnIndex);
//this.preloadMisses(rowIndex,columnIndex);
////}
////intvalue=Integer.parseInt(up.getText());
////rows[rowIndex]=this.getMiss(++value);
//returnrows[rowIndex];
//}
//else{
returncd;
//}
}
publicvoidcalculateAnalysis(){
this.gci=getGameCardIterator();
List<String>categories=this.buildCategories();
this.columns=newArrayList<String>(1+categories.size());
this.columns.add(this.columnOne);
this.columns.addAll(categories);
this.tcols=newHashMap<String,CellData[]>();
this.dataChart=newLinkedHashMap<String,Integer>();
for(Stringc:this.columns){
CellData[]line=newCellData[(int)this.gci.size()];
Arrays.fill(line,this.miss);
this.tcols.put(c,line);
this.dataChart.put(c,newInteger(0));
}
this.dataChart.remove(this.columnOne);
this.fillTableChart();
this.gci.close();
128
this.preloadMisses();
protectedabstractvoidfillTableChart();
protectedabstractList<String>buildCategories();
publicJFreeChartgetChart(){
DefaultPieDatasetdataset=newDefaultPieDataset();
Set<String>keys=this.dataChart.keySet();
for(Stringkey:keys){
dataset.setValue(key,this.dataChart.get(key));
}
JFreeChartchart=ChartFactory.createPieChart(this.getName(),
dataset,true,true,false);
PiePlotplot=(PiePlot)chart.getPlot();
PieSectionLabelGeneratorgenerator=newStandardPieSectionLabelGenerator(
"{0}{2}",newDecimalFormat("0"),newDecimalFormat("0.00%")
);
plot.setLabelGenerator(generator);
returnchart;
}
publicCellDatagetMiss(intmiss){
Integerkey=Integer.valueOf(miss);
CellDatacd=this.misses.get(key);
if(cd==null){
cd=newCellData(String.valueOf(miss),Color.WHITE,Color.LIGHT_GRAY,
false);
this.misses.put(key,cd);
}
returncd;
}
publicCellDatagetHitz(inthitz){
Integerkey=Integer.valueOf(hitz);
CellDatacd=this.hitz.get(key);
if(cd==null){
cd=newCellData(String.valueOf(hitz),Color.WHITE,Color.BLACK,true);
this.hitz.put(key,cd);
}
returncd;
}
privatevoidpreloadMisses(){
for(Strings:this.columns){
if(s.equals(this.columnOne))continue;
CellData[]rows=this.tcols.get(s);
if(!rows[0].isHit())rows[0]=this.getMiss(1);
for(inti=1;i<rows.length;++i){
CellDatacd=rows[i];
if(!cd.isHit()){
129
cd=rows[i1];
if(cd.isHit()){
rows[i]=this.getMiss(1);
}
else{
intup=Integer.parseInt(cd.getText());
rows[i]=this.getMiss(++up);
}
}
}
}
}
}
/*
*FileChooserLLG.java
*
*Createdon22deMarode2007,20:44
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.generator.GeneratorHeader;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.MainFrame;
importbr.ufsc.inf.lagar.ui.FileExtensionFilter;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importjava.awt.Dimension;
importjava.io.File;
importjava.io.IOException;
importjava.text.DateFormat;
importjava.text.NumberFormat;
importjava.util.Locale;
importjavax.swing.JEditorPane;
importjavax.swing.JFileChooser;
importjavax.swing.JOptionPane;
importjavax.swing.JScrollPane;
importjavax.swing.SwingUtilities;
importjavax.swing.filechooser.FileFilter;
/**
*
*@authorlagar
*/
publicclassFileChooserLLGextendsjavax.swing.JPanel{
publicenumChooserMode{
SAVE_MODE,
LOAD_MODE
}
privateChooserModemode=ChooserMode.LOAD_MODE;
privateJFileChooserfileChooser;
/**CreatesnewformFileChooserLLG*/
publicFileChooserLLG(){
initComponents();
130
this.fileChooser=newJFileChooser();
this.fileChooser.setMultiSelectionEnabled(false);
this.fileChooser.setAcceptAllFileFilterUsed(false);
FileFilter[]filters=fileChooser.getChoosableFileFilters();
for(FileFilterf:filters){
fileChooser.removeChoosableFileFilter(f);
}
fileChooser.addChoosableFileFilter(newFileExtensionFilter("llg",
"LagarLotteryGames(*.LLG)"));
this.infoLabel.setVisible(false);
this.numberInfoLabel.setVisible(false);
this.infoButton.setVisible(false);
this.gameTypeLabel.setVisible(false);
this.gameTypeInfo.setVisible(false);
this.spacerLabel.setVisible(false);
}
@Override
publicvoidsetEnabled(booleanenabled){
super.setEnabled(enabled);
this.fileField.setEnabled(enabled);
this.fileButton.setEnabled(enabled);
this.fileLabel.setEnabled(enabled);
}
privatevoidchooseFile(){
intreturnVal=JFileChooser.CANCEL_OPTION;
switch(mode){
caseSAVE_MODE:returnVal=this.fileChooser.showSaveDialog(null);break;
caseLOAD_MODE:returnVal=this.fileChooser.showOpenDialog(null);break;
}
if(returnVal==JFileChooser.APPROVE_OPTION){
StringselectedFile=this.fileChooser.getSelectedFile().toString();
if(!selectedFile.toLowerCase().endsWith(".llg")){
selectedFile=selectedFile+".llg";
}
this.fileField.setText(selectedFile);
if(this.mode==ChooserMode.LOAD_MODE){
GeneratorHeaderheader;
try{
header=GeneratorHeader.fetchGeneratorHeader(new
File(selectedFile));
NumberFormatnf=NumberFormat.getInstance();
this.numberInfoLabel.setText(nf.format(header.getNumberOfCards())
);
this.gameTypeInfo.setText(header.getGameName());
this.infoLabel.setVisible(true);
this.numberInfoLabel.setVisible(true);
this.infoButton.setVisible(true);
this.gameTypeLabel.setVisible(true);
this.gameTypeInfo.setVisible(true);
this.spacerLabel.setVisible(true);
}catch(IOExceptionex){
ex.printStackTrace();
131
}
}
publicStringgetFilePath(){
returnthis.fileField.getText();
}
publicChooserModegetMode(){
returnmode;
}
publicvoidsetMode(ChooserModemode){
this.mode=mode;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
fileLabel=newjavax.swing.JLabel();
fileField=newjavax.swing.JTextField();
fileButton=newjavax.swing.JButton();
infoLabel=newjavax.swing.JLabel();
infoButton=newjavax.swing.JButton();
gameTypeLabel=newjavax.swing.JLabel();
numberInfoLabel=newjavax.swing.JLabel();
gameTypeInfo=newjavax.swing.JLabel();
spacerLabel=newjavax.swing.JLabel();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
fileLabel.setText(bundle.getString("File:"));//NOI18N
fileButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/fileopen.png")));
fileButton.setText(bundle.getString("Choose.."));//NOI18N
fileButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
fileButtonActionPerformed(evt);
}
});
infoLabel.setText(bundle.getString("Number_of_cards:"));//NOI18N
infoButton.setText(bundle.getString("Show_cards"));//NOI18N
infoButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
infoButtonActionPerformed(evt);
}
});
gameTypeLabel.setText(bundle.getString("Game_type:"));//NOI18N
numberInfoLabel.setText("xxxx");
132
gameTypeInfo.setText("xxxx");
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fileLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(layout.createSequentialGroup()
.add(infoLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(numberInfoLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,369,Short.MAX_VALUE)
.addContainerGap())
.add(layout.createSequentialGroup()
.add(fileField,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
380,Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(fileButton))
.add(layout.createSequentialGroup()
.add(gameTypeLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(gameTypeInfo,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,70,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(infoButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(spacerLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,219,Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASEL
INE)
.add(fileLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
20,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(fileButton)
.add(fileField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
22,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASEL
INE)
.add(gameTypeLabel)
.add(gameTypeInfo)
.add(infoButton)
.add(spacerLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
24,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASEL
INE)
.add(infoLabel)
.add(numberInfoLabel)))
);
}//</editorfold>//GENEND:initComponents
privatevoidinfoButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_infoButtonActionPerformed
133
GameCardsInfogci=newGameCardsInfo(null,false);
gci.setGameFilePath(this.getFilePath());
gci.showGameCardsInfo();
}//GENLAST:event_infoButtonActionPerformed
privatevoidfileButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_fileButtonActionPerformed
this.chooseFile();
}//GENLAST:event_fileButtonActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JButtonfileButton;
privatejavax.swing.JTextFieldfileField;
privatejavax.swing.JLabelfileLabel;
privatejavax.swing.JLabelgameTypeInfo;
privatejavax.swing.JLabelgameTypeLabel;
privatejavax.swing.JButtoninfoButton;
privatejavax.swing.JLabelinfoLabel;
privatejavax.swing.JLabelnumberInfoLabel;
privatejavax.swing.JLabelspacerLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*FileExtensionFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui;
importjava.io.File;
importjavax.swing.filechooser.FileFilter;
publicclassFileExtensionFilterextendsFileFilter{
privateStringm_description=null;
privateStringm_extension=null;
publicFileExtensionFilter(Stringextension,Stringdescription){
m_description=description;
m_extension=extension;
}
publicStringgetDescription(){
134
returnm_description;
}
publicbooleanaccept(Filef){
if(f==null)
returnfalse;
if(f.isDirectory())returntrue;
returnf.getName().toLowerCase().endsWith(m_extension);
}
}
/*
*Filterable.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter;
importbr.ufsc.inf.lagar.main.GameCard;
importjavax.swing.JTextField;
/**
*
*@authorlagar
*/
publicinterfaceFilterable{
publicstaticfinalStringOR_SEPARATOR="\\|";//justthe"|"
publicStringgetShortName();
publicStringgetFullName();
publicStringgetDescription();
publicStringgetFilterHelp();
/**
*Setifthefilterwillbeinacceptorrejectmode.
*@parammodetruemeansacceptmode,falsemeansrejectmode.
*/
publicvoidsetAcceptReject(booleanmode);
publicvoidsetTextInput(Stringinput)throwsTextInputFilterException;
/**
135
*SubmittheGameCardtothefilter.
*@paramcardtheGameCardtobetestedagainstthefilter
*@returntrueifthecardpassedthefiltertest,falseifthefilterrejected
thecard.
*/
publicbooleanfilter(GameCardcard);
publicbooleanacceptGame(StringgameName);
}
/*
*FilterManager.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.generator.GeneratorHeader;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importbr.ufsc.inf.lagar.ui.ProgressInterface;
importbr.ufsc.inf.lagar.ui.panels.filter.SingleFilterPanel;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.text.NumberFormat;
importjava.util.List;
importjava.util.zip.Deflater;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipOutputStream;
publicclassFilterManagerimplementsProgressInterface{
privatebooleancancel;
privateintpassedCards=0;
privateintcurrentCard=0;
privatelongtotal;
privateList<SingleFilterPanel>filters;
privateFileloadCards;
privateFilesaveCards;
privateGeneratorHeaderheader;
/**CreatesanewinstanceofFilterManager*/
136
publicFilterManager(FileloadCards,FilesaveCards,List<SingleFilterPanel>
filters)throwsIOException{
this.filters=filters;
this.loadCards=loadCards;
this.saveCards=saveCards;
if(!saveCards.isFile()||!saveCards.canWrite()||
saveCards.equals(loadCards)){
thrownewIOException("Can'tsavefilteredcardsonchoosenlocation.
Chooseanother.");
}
this.header=GeneratorHeader.fetchGeneratorHeader(loadCards);
this.total=this.header.getNumberOfCards();
publicvoidrunFilters()throwsIOException{
FileOutputStreamfos=newFileOutputStream(saveCards);
ZipOutputStreamzos=newZipOutputStream(fos);
zos.setLevel(Deflater.BEST_SPEED);
DataOutputStreamdos=newDataOutputStream(zos);
zos.putNextEntry(newZipEntry(LagarLotteryGlobals.GENERATED_CARDS_NAME));
GenCardIOinput=newGenCardIO(loadCards);
while(input.hasNext()){
booleanok=true;
++currentCard;
GameCardgc=input.next();
for(SingleFilterPanelsfp:filters){
Filterablef=sfp.getFilter();
if(!f.filter(gc)){
ok=false;
break;
}
}
if(ok){
dos.write(gc.getBalls());
++passedCards;
}
if(this.cancel){
zos.closeEntry();
dos.close();
this.saveCards.delete();
thrownewIOException("Cancelled");
}
}
dos.flush();
zos.closeEntry();
header.setNumberOfCards(getPassedCards());
zos.putNextEntry(newZipEntry(LagarLotteryGlobals.GENERATED_HEADER_NAME));
137
header.saveToStream(dos);
dos.flush();
zos.closeEntry();
dos.close();
publicvoidcancel(){
this.cancel=true;
}
publicStringgetProgressText(){
NumberFormatnf=NumberFormat.getInstance();
returnnf.format(this.currentCard)+"of"+nf.format(total)+"
filtered.";
}
publicintgetProgressValue(){
returnthis.currentCard;
}
publicintgetMaxProgressValue(){
return(int)this.total;
}
publicintgetPassedCards(){
returnpassedCards;
}
}
/*
*FilterPanel.java
*
*Createdon29deMarode2007,21:02
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.filter.FilterManager;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.ui.dialog.ProgressDialog;
importbr.ufsc.inf.lagar.ui.panels.filter.SingleFilterPanel;
importjava.io.File;
importjava.io.IOException;
importjava.text.NumberFormat;
importjava.util.List;
importjavax.swing.JOptionPane;
importjavax.swing.SwingUtilities;
/**
*
*@authorlagar
*/
publicclassFilterPanelextendsjavax.swing.JPanel{
/**CreatesnewformFilterPanel*/
publicFilterPanel(){
initComponents();
this.fileChooserSave.setMode(FileChooserLLG.ChooserMode.SAVE_MODE);
}
138
publicvoidloadAvailableFilters()throwsException{
this.filterSelectPanel1.loadAvailableFilters();
}
publicbooleanvalidateInput(){
if(this.fileChooserLoad.getFilePath()==null||
this.fileChooserLoad.getFilePath().equals("")){
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Choose_a_game_to_filter."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
if(this.filterSelectPanel1.getAddedFilters().size()==0){
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Choose_a_filter."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
if(this.fileChooserSave.getFilePath()==null||
this.fileChooserSave.getFilePath().equals("")){
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Choose_a_file_to_save_the_filtered_cards."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
List<SingleFilterPanel>filters=this.filterSelectPanel1.getAddedFilters();
for(SingleFilterPanelsfp:filters){
try{
sfp.getFilter().setTextInput(sfp.getFilterField().getText());
}catch(TextInputFilterExceptionex){
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("<html>Filter_<b>")+sfp.getPosition()+java.util.ResourceBundle.getB
undle("resources/bundles/lagarLottery").getString("</b>_has_input_errors.</html>"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLo
ttery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
}
139
returntrue;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
infoPanel=newjavax.swing.JPanel();
infoLabel=newjavax.swing.JLabel();
loadPanel=newjavax.swing.JPanel();
fileChooserLoad=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
mainPanel=newjavax.swing.JPanel();
filterSelectPanel1=new
br.ufsc.inf.lagar.ui.panels.filter.FilterSelectPanel();
savePanel=newjavax.swing.JPanel();
fileChooserSave=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
sp1=newjavax.swing.JLabel();
sp2=newjavax.swing.JLabel();
runFiltersButton=newjavax.swing.JButton();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
simpleInternalFrame1.setTitle(bundle.getString("Filters"));//NOI18N
infoLabel.setText(bundle.getString("Use_this_module_to_eliminate_cards_from_a
_generated_cards_file_(LLG)."));//NOI18N
org.jdesktop.layout.GroupLayoutinfoPanelLayout=new
org.jdesktop.layout.GroupLayout(infoPanel);
infoPanel.setLayout(infoPanelLayout);
infoPanelLayout.setHorizontalGroup(
infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(infoPanelLayout.createSequentialGroup()
.addContainerGap()
.add(infoLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,561,
Short.MAX_VALUE)
.addContainerGap())
);
infoPanelLayout.setVerticalGroup(
infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(infoPanelLayout.createSequentialGroup()
.addContainerGap()
.add(infoLabel)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
loadPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getSt
ring("Cards_to_filter")));//NOI18N
org.jdesktop.layout.GroupLayoutloadPanelLayout=new
org.jdesktop.layout.GroupLayout(loadPanel);
loadPanel.setLayout(loadPanelLayout);
loadPanelLayout.setHorizontalGroup(
loadPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(fileChooserLoad,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,575,
140
Short.MAX_VALUE)
);
loadPanelLayout.setVerticalGroup(
loadPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(loadPanelLayout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(fileChooserLoad,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getSt
ring("Filters")));//NOI18N
org.jdesktop.layout.GroupLayoutmainPanelLayout=new
org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(filterSelectPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
575,Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(filterSelectPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
294,Short.MAX_VALUE)
);
savePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getSt
ring("Save_filtered_cards")));//NOI18N
org.jdesktop.layout.GroupLayoutsavePanelLayout=new
org.jdesktop.layout.GroupLayout(savePanel);
savePanel.setLayout(savePanelLayout);
savePanelLayout.setHorizontalGroup(
savePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(fileChooserSave,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,575,
Short.MAX_VALUE)
);
savePanelLayout.setVerticalGroup(
savePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(savePanelLayout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.add(fileChooserSave,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
runFiltersButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
runFiltersButton.setText(bundle.getString("Run_filters"));//NOI18N
runFiltersButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
runFiltersButtonActionPerformed(evt);
}
});
141
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(simpleInternalFrame1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
585,Short.MAX_VALUE)
.add(infoPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(loadPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(sp1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,221,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(runFiltersButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(sp2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,221,
Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING,savePanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(infoPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loadPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(savePanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAIL
ING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.B
ASELINE)
.add(sp1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(sp2,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(runFiltersButton)))
);
layout.linkSize(newjava.awt.Component[]{sp1,sp2},
org.jdesktop.layout.GroupLayout.VERTICAL);
}//</editorfold>//GENEND:initComponents
142
privatevoidrunFiltersButtonActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_runFiltersButtonActionPerformed
if(this.validateInput()){
Fileload=newFile(this.fileChooserLoad.getFilePath());
Filesave=newFile(this.fileChooserSave.getFilePath());
try{
if(load.equals(save)){
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("Can't_save_on_same_place_that_is_loading_the_cards."),
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
if(save.exists()){
save.delete();
}
save.createNewFile();
finalFilterManagerfilterManager=newFilterManager(
load,
save,
this.filterSelectPanel1.getAddedFilters());
finalProgressDialogpd=newProgressDialog(null,true,
filterManager);
pd.setLocationRelativeTo(null);
pd.getTitleLabel().setText(java.util.ResourceBundle.getBundle("resour
ces/bundles/lagarLottery").getString("Please_wait.._filtering_your_cards."));
Threadt=newThread(newRunnable(){
publicvoidrun(){
try{
filterManager.runFilters();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles
/lagarLottery").getString("Run_filters_successfully")+"\n"+
java.util.ResourceBundle.getBundle("resources/bun
dles/lagarLottery").getString("Number_of_cards_that_passed_the_filters:_")+
NumberFormat.getInstance().format(filterManager.ge
tPassedCards())+"\n"+
java.util.ResourceBundle.getBundle("resources/bund
les/lagarLottery").getString("Number_of_rejected_cards:_")+
NumberFormat.getInstance().format(filterManager.g
etMaxProgressValue()filterManager.getPassedCards()),
java.util.ResourceBundle.getBundle("resources/bundles
/lagarLottery").getString("Ok"),
JOptionPane.INFORMATION_MESSAGE);
}catch(IOExceptionex){
ex.printStackTrace();
}
finally{
143
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
pd.exit();
}
});
}
}
});
t.start();
pd.showProgressDialog();
}catch(IOExceptionex){
ex.printStackTrace();
}
}
}//GENLAST:event_runFiltersButtonActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserLoad;
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserSave;
privatebr.ufsc.inf.lagar.ui.panels.filter.FilterSelectPanelfilterSelectPanel1;
privatejavax.swing.JLabelinfoLabel;
privatejavax.swing.JPanelinfoPanel;
privatejavax.swing.JPanelloadPanel;
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JButtonrunFiltersButton;
privatejavax.swing.JPanelsavePanel;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
privatejavax.swing.JLabelsp1;
privatejavax.swing.JLabelsp2;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*FilterSelectPanel.java
*
*Createdon29deMarode2007,21:13
*/
packagebr.ufsc.inf.lagar.ui.panels.filter;
importbr.ufsc.inf.lagar.filter.Filterable;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importbr.ufsc.inf.lagar.utils.RTSI;
importjava.awt.Color;
importjava.awt.Rectangle;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.ResourceBundle;
importjavax.swing.JScrollPane;
importjavax.swing.JTextPane;
importjavax.swing.border.Border;
importjavax.swing.border.LineBorder;
144
importjavax.swing.border.MatteBorder;
/**
*
*@authorlagar
*/
publicclassFilterSelectPanelextendsjavax.swing.JPanel{
privateArrayList<SingleFilterPanel>addedFilters=new
ArrayList<SingleFilterPanel>();
privateSingleFilterPanelselectedFilter;
privateBorderdefaultBorder=newMatteBorder(0,1,1,1,Color.LIGHT_GRAY);
privateBorderselectedBorder=newLineBorder(Color.BLACK,2);
/**CreatesnewformFilterSelectPanel*/
publicFilterSelectPanel(){
initComponents();
this.buttonBar.setBackground(this.getBackground());
this.changeFilterButtonsState();
}
publicvoidloadAvailableFilters()throwsException{
GameConfigurationcurrent=GameManager.getCurrentGame();
StringpackageName="br.ufsc.inf.lagar.filter.gamefilter";
ArrayList<String>classes=RTSI.find(packageName,Filterable.class);
for(Stringclazz:classes){
clazz=packageName+"."+clazz;
Filterablefilter=(Filterable)Class.forName(clazz).newInstance();
if(filter.acceptGame(current.getName())){
this.filterCombo.addItem(filter);
}
}
this.filterCombo.setSelectedIndex(0);
publicvoidmoveUp(SingleFilterPanelsfp){
intpos=sfp.getPosition()1;
if(pos==0)return;
this.getAddedFilters().remove(pos);
pos;
this.getAddedFilters().add(pos,sfp);
this.rebuildFilterList();
}
publicvoidmoveDown(SingleFilterPanelsfp){
intpos=sfp.getPosition()1;
145
if(pos==this.getAddedFilters().size()1)return;
this.getAddedFilters().remove(pos);
++pos;
this.getAddedFilters().add(pos,sfp);
this.rebuildFilterList();
}
publicvoidremoveSfp(SingleFilterPanelsfp){
intpos=sfp.getPosition()1;
this.getAddedFilters().remove(pos);
if(pos>0){
pos;
}
if(pos<this.getAddedFilters().size()){
this.setSelectedFilter(this.getAddedFilters().get(pos));
}
else{
this.setSelectedFilter(null);
}
this.changeFilterButtonsState();
this.rebuildFilterList();
}
publicvoidsetSelectedFilter(SingleFilterPanelsfp){
this.selectedFilter=sfp;
for(SingleFilterPanels:addedFilters){
s.setBorder(this.defaultBorder);
}
if(this.selectedFilter!=null){
this.selectedFilter.setBorder(this.selectedBorder);
}
this.repaint();
privatevoidrebuildFilterList(){
this.selFilterPanel.removeAll();
for(inti=0;i<this.getAddedFilters().size();++i){
SingleFilterPanelsfp=this.getAddedFilters().get(i);
sfp.setPosition(i+1);
this.selFilterPanel.add(sfp);
}
this.scrollPane.revalidate();
this.repaint();
}
/**Thismethodiscalledfromwithintheconstructorto
146
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
fLabel=newjavax.swing.JLabel();
filterCombo=newjavax.swing.JComboBox();
addButton=newjavax.swing.JButton();
mainPanel=newjavax.swing.JPanel();
scrollPane=newjavax.swing.JScrollPane();
selFilterPanel=newjavax.swing.JPanel();
filterButtonsPanel=newjavax.swing.JPanel();
buttonBar=newcom.l2fprod.common.swing.JButtonBar();
helpButton=newjavax.swing.JButton();
removeButton=newjavax.swing.JButton();
upButton=newjavax.swing.JButton();
downButton=newjavax.swing.JButton();
fLabel.setLabelFor(filterCombo);
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
fLabel.setText(bundle.getString("Filter:"));//NOI18N
filterCombo.setBackground(newjava.awt.Color(255,255,255));
addButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/add.png")));
addButton.setText(bundle.getString("Add"));//NOI18N
addButton.setMargin(newjava.awt.Insets(2,2,2,2));
addButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
addButtonActionPerformed(evt);
}
});
scrollPane.setBorder(null);
scrollPane.setDoubleBuffered(true);
selFilterPanel.setLayout(newjavax.swing.BoxLayout(selFilterPanel,
javax.swing.BoxLayout.Y_AXIS));
scrollPane.setViewportView(selFilterPanel);
filterButtonsPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(1,
1,0,0,newjava.awt.Color(243,243,243)));
buttonBar.setBorder(null);
helpButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/help.png")));
helpButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
helpButton.setMargin(newjava.awt.Insets(1,1,1,1));
helpButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
helpButtonActionPerformed(evt);
}
});
removeButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/cancel.png")));
removeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
removeButton.setMargin(newjava.awt.Insets(1,1,1,1));
removeButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
147
removeButtonActionPerformed(evt);
}
});
upButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/up.png")));
upButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
upButton.setMargin(newjava.awt.Insets(1,1,1,1));
upButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
upButtonActionPerformed(evt);
}
});
downButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/down.png")));
downButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
downButton.setMargin(newjava.awt.Insets(1,1,1,1));
downButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
downButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutbuttonBarLayout=new
org.jdesktop.layout.GroupLayout(buttonBar);
buttonBar.setLayout(buttonBarLayout);
buttonBarLayout.setHorizontalGroup(
buttonBarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(helpButton)
.add(upButton)
.add(downButton)
.add(removeButton)
);
buttonBarLayout.setVerticalGroup(
buttonBarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(buttonBarLayout.createSequentialGroup()
.add(28,28,28)
.add(helpButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(upButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(downButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(removeButton)
.addContainerGap(157,Short.MAX_VALUE))
);
org.jdesktop.layout.GroupLayoutfilterButtonsPanelLayout=new
org.jdesktop.layout.GroupLayout(filterButtonsPanel);
filterButtonsPanel.setLayout(filterButtonsPanelLayout);
filterButtonsPanelLayout.setHorizontalGroup(
filterButtonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLay
out.LEADING)
.add(buttonBar,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
filterButtonsPanelLayout.setVerticalGroup(
filterButtonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLay
out.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,buttonBar,
148
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayoutmainPanelLayout=new
org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
mainPanelLayout.createSequentialGroup()
.add(scrollPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,448,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filterButtonsPanel,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(scrollPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,292,
Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,filterButtonsPanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,35,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filterCombo,0,369,Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(addButton))
.add(org.jdesktop.layout.GroupLayout.TRAILING,mainPanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.B
ASELINE)
.add(addButton)
.add(filterCombo,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(fLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
149
}//</editorfold>//GENEND:initComponents
privatevoiddownButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_downButtonActionPerformed
this.moveDown(this.selectedFilter);
}//GENLAST:event_downButtonActionPerformed
privatevoidupButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_upButtonActionPerformed
this.moveUp(this.selectedFilter);
}//GENLAST:event_upButtonActionPerformed
privatevoidremoveButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_removeButtonActionPerformed
this.removeSfp(this.selectedFilter);
}//GENLAST:event_removeButtonActionPerformed
privatevoidhelpButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_helpButtonActionPerformed
DecisionDialogdd=newDecisionDialog(null,false);
JTextPanetextPane=newJTextPane();
textPane.setText(this.selectedFilter.getFilter().getFilterHelp());
JScrollPanepane=newJScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dd.getMainPanel().add(pane,pane.getClass().getName());
dd.getButtonsPanel().setVisible(false);
dd.getTitlePanel().setTitle(this.selectedFilter.getFilter().getShortName());
dd.setTitle(ResourceBundle.getBundle("resources/bundles/lagarLottery").getStr
ing("Help"));
dd.setVisible(true);
}//GENLAST:event_helpButtonActionPerformed
privatevoidaddButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_addButtonActionPerformed
FilterablefilterOriginal=(Filterable)this.filterCombo.getSelectedItem();
Filterablefilter;
try{
filter=(Filterable)filterOriginal.getClass().newInstance();
}catch(Exceptionex){
thrownewRuntimeException(ex);
}
SingleFilterPanelsfp=newSingleFilterPanel(filter,
this.getAddedFilters().size()+1,this);
sfp.setBorder(this.defaultBorder);
this.getAddedFilters().add(sfp);
this.setSelectedFilter(sfp);
this.selFilterPanel.add(sfp);
this.scrollPane.revalidate();
this.changeFilterButtonsState();
this.repaint();
}//GENLAST:event_addButtonActionPerformed
privatevoidchangeFilterButtonsState(){
150
booleanenabled=this.selectedFilter!=null;
this.helpButton.setEnabled(enabled);
this.removeButton.setEnabled(enabled);
this.upButton.setEnabled(enabled);
this.downButton.setEnabled(enabled);
}
publicArrayList<SingleFilterPanel>getAddedFilters(){
returnaddedFilters;
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JButtonaddButton;
privatecom.l2fprod.common.swing.JButtonBarbuttonBar;
privatejavax.swing.JButtondownButton;
privatejavax.swing.JLabelfLabel;
privatejavax.swing.JPanelfilterButtonsPanel;
privatejavax.swing.JComboBoxfilterCombo;
privatejavax.swing.JButtonhelpButton;
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JButtonremoveButton;
privatejavax.swing.JScrollPanescrollPane;
privatejavax.swing.JPanelselFilterPanel;
privatejavax.swing.JButtonupButton;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*GameCardIterator.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importjava.io.IOException;
importjava.util.Iterator;
/**
*
*@authorlagar
*/
publicinterfaceGameCardIteratorextendsIterator<GameCard>{
publiclongsize();
151
publicintgetBallsPerCard();
publicvoidnext(GameCardcardBuffer);
publicvoidclose();
}
/**
*DrawResult.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importjava.text.SimpleDateFormat;
importjava.util.*;
/**
*@authorEuclidesPinheirodeMelo
*Representsonedrawresultinformation.
*/
publicclassGameCardimplementsComparable<GameCard>{
intserial;
Datedate;
privatebyte[]balls;
publicGameCard(){
publicGameCard(intserial,Datedate,intsize){
//TODOAutogeneratedconstructorstub
this.setBalls(newbyte[size]);
this.date=date;
this.serial=serial;
}
@Override
publicStringtoString(){
SimpleDateFormatsdf=newSimpleDateFormat("dd/MM/yyyy");
StringBuildersb=newStringBuilder(100);
sb.append(this.getSerial());
sb.append("::");
152
for(bytei:this.balls){
sb.append(i);
sb.append("");
}
if(this.date!=null)
sb.append(sdf.format(this.date));
returnsb.toString();
}
publicvoidsetBall(byteball,intpos){
this.balls[pos]=ball;
}
/**
*@returnReturnstheballs.
*/
publicbyte[]getBalls(){
returnthis.balls;
}
publicvoidsetBalls(byte[]balls){
this.balls=balls;
}
/**
*@returnReturnsthedate.
*/
publicDategetDate(){
returnthis.date;
}
/**
*@paramdateThedatetoset.
*/
publicvoidsetDate(Datedate){
this.date=date;
}
/**
*@returnReturnstheserial.
*/
publicintgetSerial(){
returnthis.serial;
}
/**
*@paramserialTheserialtoset.
*/
publicvoidsetSerial(intserial){
this.serial=serial;
}
publicintcompareTo(GameCardo){
if(this.serial>o.getSerial()){
return1;
}
elseif(this.serial<o.getSerial()){
return1;
}
return0;
153
}
}
/*
*GameCardLayout.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importjava.awt.geom.Point2D;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
publicclassGameCardLayout{
privatedoublewidth;
privatedoubleheigth;
privatedoubleballWidth;
privatedoubleballHeigth;
privateHashMap<Integer,Point2D.Double>balls=newHashMap<Integer,
Point2D.Double>();
privateList<ExtendedBall>extendedBalls=newArrayList<ExtendedBall>();
privateExtendedTextextendedText=null;
/**
*CreatesanewinstanceofGameCardLayout
*/
publicGameCardLayout(){
}
publicstaticclassExtendedBall{
privateStringdescription;
privatebooleanrequired;
privateHashMap<Integer,Point2D.Double>balls=newHashMap<Integer,
Point2D.Double>();
publicbooleanisRequired(){
returnrequired;
154
}
publicvoidsetRequired(booleanrequired){
this.required=required;
}
publicHashMap<Integer,Point2D.Double>getBalls(){
returnballs;
}
publicvoidsetBalls(HashMap<Integer,Point2D.Double>balls){
this.balls=balls;
}
publicStringgetDescription(){
returndescription;
}
publicvoidsetDescription(Stringdescription){
this.description=description;
}
}
publicstaticclassExtendedText{
privatedoublex;
privatedoubley;
privatedoublewidth;
privatedoubleheight;
publicdoublegetX(){
returnx;
}
publicvoidsetX(doublex){
this.x=x;
}
publicdoublegetY(){
returny;
}
publicvoidsetY(doubley){
this.y=y;
}
publicdoublegetWidth(){
returnwidth;
}
publicvoidsetWidth(doublewidth){
this.width=width;
}
publicdoublegetHeight(){
returnheight;
}
publicvoidsetHeight(doubleheight){
this.height=height;
}
}
155
publicdoublegetWidth(){
returnwidth;
}
publicvoidsetWidth(doublewidth){
this.width=width;
}
publicdoublegetHeigth(){
returnheigth;
}
publicvoidsetHeigth(doubleheigth){
this.heigth=heigth;
}
publicdoublegetBallWidth(){
returnballWidth;
}
publicvoidsetBallWidth(doubleballWidth){
this.ballWidth=ballWidth;
}
publicdoublegetBallHeigth(){
returnballHeigth;
}
publicvoidsetBallHeigth(doubleballHeigth){
this.ballHeigth=ballHeigth;
}
publicHashMap<Integer,Point2D.Double>getBalls(){
returnballs;
}
publicvoidsetBalls(HashMap<Integer,Point2D.Double>balls){
this.balls=balls;
}
publicList<ExtendedBall>getExtendedBalls(){
returnextendedBalls;
}
publicvoidsetExtendedBalls(List<ExtendedBall>extendedBalls){
this.extendedBalls=extendedBalls;
}
publicExtendedTextgetExtendedText(){
returnextendedText;
}
publicvoidsetExtendedText(ExtendedTextextendedText){
this.extendedText=extendedText;
}
}
/*
*GameCardPrinter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
156
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.printer;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Graphics;
importjava.awt.print.PageFormat;
importjava.awt.print.Printable;
importjava.awt.print.PrinterException;
importjava.io.File;
importjava.io.IOException;
publicabstractclassGameCardPrinterimplementsPrintable{
/**CreatesanewinstanceofGameCardPrinter*/
publicGameCardPrinter(){
}
publicabstractvoidsetFile(FilegameCard)throwsIOException;
publicabstractintprint(Graphicsg,PageFormatpf,intpageIndex)throws
PrinterException;
protectedabstractvoidprintExtendedText(GameCardgc,Graphicsg,PageFormat
pf,intpageIndex)throwsPrinterException;
protectedabstractvoidprintExtendedBalls(GameCardgc,Graphicsg,PageFormat
pf,intpageIndex)throwsPrinterException;
protecteddoublecmToPixel(doublecm){
doubleinch=this.cmToInch(cm);
returninch*72;
}
protecteddoublecmToInch(doublecm){
returncm/2.54;
}
}
/*
*GameCardsInfo.java
*
*Createdon17deAbrilde2007,21:58
*/
157
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.ui.FileExtensionFilter;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.io.StringWriter;
importjava.io.Writer;
importjava.text.NumberFormat;
importjavax.swing.JFileChooser;
importjavax.swing.JOptionPane;
importjavax.swing.ProgressMonitor;
importjavax.swing.SwingUtilities;
importjavax.swing.filechooser.FileFilter;
/**
*
*@authorlagar
*/
publicclassGameCardsInfoextendsjavax.swing.JDialog{
privateStringgameFilePath;
/**CreatesnewformGameCardsInfo*/
publicGameCardsInfo(java.awt.Frameparent,booleanmodal){
super(parent,modal);
initComponents();
this.setLocationRelativeTo(parent);
}
publicvoidshowGameCardsInfo(){
Threadt=newThread(newRunnable(){
publicvoidrun(){
StringWritersb=newStringWriter();
try{
writeCards(sb,true);
}catch(IOExceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error_loading_cards"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
jEditorPane1.setText(sb.toString());
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
GameCardsInfo.this.setVisible(true);
}
});
}
});
158
t.start();
privatevoidwriteCards(Writersb,booleanonScreen)throwsIOException{
finalStringfilePath=this.gameFilePath;
GenCardIOio=newGenCardIO(newFile(filePath));
try{
intdigits=String.valueOf(io.size()).length();
if(onScreen){
if(io.size()>1000){
sb.write(java.util.ResourceBundle.getBundle("resources/bundles/la
garLottery").getString("Too_much_cards_to_show_on_screen._Please_export_to_file_using
_the_button_on_the_menu."));
return;
}
}
ProgressMonitorpm=null;
if(!onScreen){
pm=newProgressMonitor(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Exporting.."),
"",
0,
(int)io.size());
pm.setMillisToDecideToPopup(50);
pm.setMillisToPopup(50);
}
NumberFormatnf=NumberFormat.getIntegerInstance();
nf.setMinimumIntegerDigits(digits);
NumberFormatnfb=NumberFormat.getIntegerInstance();
nfb.setMinimumIntegerDigits(2);
sb.append("<html>");
GameCardgc=newGameCard(0,null,io.getBallsPerCard());
intp=0;
while(io.hasNext()){
io.next(gc);
sb.append("<b>");
sb.append(nf.format(gc.getSerial()));
sb.append("</b>");
sb.append("");
for(bytei:gc.getBalls()){
sb.append("");
sb.append(nfb.format(i));
sb.append("");
}
sb.append("<br>\n");
if(pm!=null){
159
if(pm.isCanceled()){
break;
}
pm.setProgress(++p);
}
}
sb.append("</html>");
}
finally{
io.close();
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
jPanel1=newjavax.swing.JPanel();
jScrollPane1=newjavax.swing.JScrollPane();
jEditorPane1=newjavax.swing.JEditorPane();
jMenuBar1=newjavax.swing.JMenuBar();
jMenu1=newjavax.swing.JMenu();
jMenuItem1=newjavax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
setTitle(bundle.getString("Cards_on_file"));//NOI18N
jEditorPane1.setContentType("text/html");
jScrollPane1.setViewportView(jEditorPane1);
org.jdesktop.layout.GroupLayoutjPanel1Layout=new
org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,574,
Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,303,
Short.MAX_VALUE)
);
jMenu1.setText(bundle.getString("Menu"));//NOI18N
jMenuItem1.setText(bundle.getString("Export_cards_to_file"));//NOI18N
jMenuItem1.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
160
setJMenuBar(jMenuBar1);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
pack();
}//</editorfold>//GENEND:initComponents
privatevoidjMenuItem1ActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_jMenuItem1ActionPerformed
JFileChooserchooser=newJFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
FileFilter[]filters=chooser.getChoosableFileFilters();
for(FileFilterf:filters){
chooser.removeChoosableFileFilter(f);
}
chooser.addChoosableFileFilter(newFileExtensionFilter("html",
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").
getString("Html_file_(*.html)")));
intret=chooser.showSaveDialog(this);
if(ret==JFileChooser.APPROVE_OPTION){
Stringfp=chooser.getSelectedFile().getPath();
if(!fp.toLowerCase().endsWith(".html")&&
!fp.toLowerCase().endsWith(".htm")){
fp=fp+".html";
}
finalFilef=newFile(fp);
Threadt=newThread(newRunnable(){
publicvoidrun(){
Writerw=null;
try{
w=newBufferedWriter(newOutputStreamWriter(new
FileOutputStream(f)));
writeCards(w,false);
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles
/lagarLottery").getString("File_exported"),
java.util.ResourceBundle.getBundle("resources/bundles
161
/lagarLottery").getString("OK"),
JOptionPane.INFORMATION_MESSAGE);
}catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles
/lagarLottery").getString("Failed"),
java.util.ResourceBundle.getBundle("resources/bundles
/lagarLottery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
}
finally{
if(w!=null){
try{w.close();
}catch(IOExceptionex){
}
}
}
}
});
t.start();
}//GENLAST:event_jMenuItem1ActionPerformed
publicStringgetGameFilePath(){
returngameFilePath;
}
publicvoidsetGameFilePath(StringgameFilePath){
this.gameFilePath=gameFilePath;
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JEditorPanejEditorPane1;
privatejavax.swing.JMenujMenu1;
privatejavax.swing.JMenuBarjMenuBar1;
privatejavax.swing.JMenuItemjMenuItem1;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JScrollPanejScrollPane1;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*GameChooserPanel.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
162
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.ArrayList;
importjava.util.Enumeration;
importjava.util.List;
importjavax.swing.AbstractButton;
importjavax.swing.JPanel;
importjavax.swing.JRadioButton;
/**
*
*@authorlagar
*/
publicclassGameChooserPanelextendsJPanelimplementsActionListener{
privateList<RadioPanel>radioButtons=newArrayList<RadioPanel>();
privateDecisionDialogdecisionDialog=null;
privateStringselectedGame=null;
/**CreatesnewformGameChooserPanel*/
publicGameChooserPanel(){
initComponents();
}
publicGameChooserPanel(intnumOptions){
this();
publicvoidaddOption(Stringoption){
RadioPanelrp=newRadioPanel();
rp.getRadioButton().setText(""+option+"");
this.radioGroup.add(rp.getRadioButton());
this.bodyPanel.add(rp);
this.radioButtons.add(rp);
radioButtons.get(0).getRadioButton().setSelected(true);
}
publicStringgetSelectedGame(){
this.decisionDialog=newDecisionDialog(null,true);
this.decisionDialog.getOkButton().addActionListener(this);
this.decisionDialog.getCancelButton().addActionListener(this);
this.decisionDialog.getMainPanel().add(this,"gameChooser");
this.decisionDialog.getTitlePanel().setTitle(java.util.ResourceBundle.getBund
le("resources/bundles/lagarLottery").getString("Choose_a_game"));
this.decisionDialog.pack();
this.decisionDialog.setVisible(true);
returnthis.selectedGame.trim();
163
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
radioGroup=newjavax.swing.ButtonGroup();
bodyPanel=newjavax.swing.JPanel();
bodyPanel.setLayout(newjavax.swing.BoxLayout(bodyPanel,
javax.swing.BoxLayout.Y_AXIS));
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(27,27,27)
.add(bodyPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,361,
Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(bodyPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,276,
Short.MAX_VALUE)
.addContainerGap())
);
}//</editorfold>//GENEND:initComponents
publicvoidactionPerformed(ActionEvente){
Stringaction=e.getActionCommand();
if(action.equals(this.decisionDialog.getOkButton().getText())){
Enumeration<AbstractButton>buttons=this.radioGroup.getElements();
while(buttons.hasMoreElements()){
AbstractButtonb=buttons.nextElement();
if(this.radioGroup.isSelected(b.getModel())){
this.selectedGame=b.getText();
break;
}
}
}
this.decisionDialog.dispose();
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JPanelbodyPanel;
privatejavax.swing.ButtonGroupradioGroup;
//Endofvariablesdeclaration//GENEND:variables
164
}
/*
*GameConfiguration.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.main.GameResults;
importbr.ufsc.inf.lagar.printer.DefaultGameCardPrinter;
importbr.ufsc.inf.lagar.printer.GameCardPrinter;
publicclassGameConfiguration{
privateStringname;
privateintnumbersPerCard;
privateintminNumbersToChoose;
privateintmaxNumbersToChoose;
privateintnumbersPerDrawing;
privateintnumbersPerLine;
privateGameCardLayoutcardLayout;
privateGameResultsgameResults;
privateGameCardPrintergameCardPrinter=newDefaultGameCardPrinter();//
default
/**CreatesanewinstanceofGameConfiguration*/
publicGameConfiguration(){
}
publicGameResultIteratorgetGameCardIterator(intbegin,intend,intjump){
returnnewGameResultIterator(this.getGameResults(),begin,end,jump);
}
publicStringgetName(){
returnname;
}
protectedvoidsetName(Stringname){
this.name=name;
}
publicGameResultsgetGameResults(){
165
returngameResults;
}
protectedvoidsetGameResults(GameResultsgameResults){
this.gameResults=gameResults;
}
publicintgetNumbersPerCard(){
returnnumbersPerCard;
}
publicvoidsetNumbersPerCard(intnumbersPerCard){
this.numbersPerCard=numbersPerCard;
}
publicintgetMinNumbersToChoose(){
returnminNumbersToChoose;
}
publicvoidsetMinNumbersToChoose(intminNumbersToChoose){
this.minNumbersToChoose=minNumbersToChoose;
}
publicintgetMaxNumbersToChoose(){
returnmaxNumbersToChoose;
}
publicvoidsetMaxNumbersToChoose(intmaxNumbersToChoose){
this.maxNumbersToChoose=maxNumbersToChoose;
}
@Override
publicStringtoString(){
StringBuildersb=newStringBuilder(50);
sb.append("Name:"+this.name);sb.append("\n");
sb.append("NumbersPerCard:"+this.numbersPerCard);sb.append("\n");
sb.append("NumbersPerDrawing:"+this.numbersPerDrawing);sb.append("\n");
sb.append("minNumbersChoose:"+this.minNumbersToChoose);sb.append("\n");
sb.append("maxNumbersChoose:"+this.maxNumbersToChoose);sb.append("\n");
returnsb.toString();
}
publicintgetNumbersPerDrawing(){
returnnumbersPerDrawing;
}
publicvoidsetNumbersPerDrawing(intnumbersPerDrawing){
this.numbersPerDrawing=numbersPerDrawing;
}
publicGameCardLayoutgetCardLayout(){
returncardLayout;
}
publicvoidsetCardLayout(GameCardLayoutcardLayout){
this.cardLayout=cardLayout;
}
publicGameCardPrintergetGameCardPrinter(){
returngameCardPrinter;
}
166
publicvoidsetGameCardPrinter(GameCardPrintergameCardPrinter){
this.gameCardPrinter=gameCardPrinter;
}
publicintgetNumbersPerLine(){
returnnumbersPerLine;
}
publicvoidsetNumbersPerLine(intnumbersPerLine){
this.numbersPerLine=numbersPerLine;
}
}
/*
*GameConfigurationParser.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.printer.GameCardPrinter;
importbr.ufsc.inf.lagar.resultloader.ResultLoader;
importbr.ufsc.inf.lagar.utils.LocalEntityResolver;
importjava.awt.geom.Point2D;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.MalformedURLException;
importjava.util.List;
importorg.jdom.Document;
importorg.jdom.Element;
importorg.jdom.JDOMException;
importorg.jdom.input.SAXBuilder;
publicclassGameConfigurationParser{
/**CreatesanewinstanceofGameConfigurationParser*/
publicGameConfigurationParser(){
}
publicGameConfigurationparse(InputStreamin)throwsClassNotFoundException,
InstantiationException,IllegalAccessException,MalformedURLException,
JDOMException,IOException{
GameConfigurationgc=newGameConfiguration();
SAXBuildersaxBuilder=newSAXBuilder(true);
167
saxBuilder.setEntityResolver(newLocalEntityResolver("lagarLotterygametype
dtd","/gametypes/gametype.dtd"));
Documentdoc=saxBuilder.build(in);
Elementroot=doc.getRootElement();
gc.setName(root.getChildTextTrim("name"));
gc.setNumbersPerCard(Integer.parseInt(root.getChildTextTrim("numbersPerCard")
));
gc.setNumbersPerDrawing(Integer.parseInt(root.getChildTextTrim("numbersPerDra
wing")));
gc.setMinNumbersToChoose(Integer.parseInt(root.getChildTextTrim("minNumbersTo
Choose")));
gc.setMaxNumbersToChoose(Integer.parseInt(root.getChildTextTrim("maxNumbersTo
Choose")));
gc.setNumbersPerLine(Integer.parseInt(root.getChildTextTrim("numbersPerLine")
));
//resultloader
ElementresultLoader=root.getChild("resultLoader");
StringclassName=resultLoader.getChildTextTrim("class");
StringresultPath=resultLoader.getChildTextTrim("resultPath");
ClassrlClazz=Class.forName(className);
ResultLoaderrl=(ResultLoader)rlClazz.newInstance();
rl.setResultPath(resultPath);
GameResultsgameResults=newGameResults();
gameResults.setResultLoader(rl);
gc.setGameResults(gameResults);
//gamecardlayout
GameCardLayoutgcl=newGameCardLayout();
ElementcardLayout=root.getChild("cardLayout");
StringcardPrinterclazz=
cardLayout.getChild("gamePrinter").getAttributeValue("class").trim();
ClasscpClazz=Class.forName(cardPrinterclazz);
GameCardPrintergameCardPrinter=(GameCardPrinter)cpClazz.newInstance();
gc.setGameCardPrinter(gameCardPrinter);
gcl.setWidth(Double.parseDouble(cardLayout.getChildTextTrim("width")));
gcl.setHeigth(Double.parseDouble(cardLayout.getChildTextTrim("height")));
gcl.setBallWidth(Double.parseDouble(cardLayout.getChildTextTrim("ballWidth"))
);
gcl.setBallHeigth(Double.parseDouble(cardLayout.getChildTextTrim("ballHeight"
)));
List<Element>balls=cardLayout.getChildren("ball");
for(Elementb:balls){
Integern=Integer.valueOf(b.getAttributeValue("n"));
doublex=Double.parseDouble(b.getAttributeValue("x"));
doubley=Double.parseDouble(b.getAttributeValue("y"));
Point2D.Doublepoint=newPoint2D.Double(x,y);
gcl.getBalls().put(n,point);
}
//extendedballs
List<Element>extBalls=cardLayout.getChildren("extendedBall");
for(ElementexBall:extBalls){
168
GameCardLayout.ExtendedBallgcex=newGameCardLayout.ExtendedBall();
Stringdesc=exBall.getChildTextTrim("description");
booleanrequired=
Boolean.parseBoolean(exBall.getChildTextTrim("required"));
gcex.setDescription(desc);
gcex.setRequired(required);
List<Element>bbx=exBall.getChildren("ball");
for(Elementbx:bbx){
Integern=Integer.valueOf(bx.getAttributeValue("n"));
doublex=Double.parseDouble(bx.getAttributeValue("x"));
doubley=Double.parseDouble(bx.getAttributeValue("y"));
Point2D.Doublepoint=newPoint2D.Double(x,y);
gcex.getBalls().put(n,point);
gcl.getExtendedBalls().add(gcex);
}
}
ElementextText=cardLayout.getChild("extendedText");
if(extText!=null){
GameCardLayout.ExtendedTextxt=newGameCardLayout.ExtendedText();
xt.setX(Double.parseDouble(extText.getAttributeValue("x")));
xt.setY(Double.parseDouble(extText.getAttributeValue("y")));
xt.setWidth(Double.parseDouble(extText.getAttributeValue("width")));
xt.setHeight(Double.parseDouble(extText.getAttributeValue("height")));
gcl.setExtendedText(xt);
}
gc.setCardLayout(gcl);
returngc;
}
}
/*
*GameFactoryTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
169
packagebr.ufsc.inf.lagar.core.base;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importjunit.framework.*;
importbr.ufsc.inf.lagar.utils.RTSI;
importjava.util.ArrayList;
importjava.util.List;
/**
*
*@authorlagar
*/
publicclassGameFactoryTestextendsTestCase{
publicvoidtestLoadGames(){
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
assertNotNull(availableGames);
assertTrue(availableGames.size()!=0);
for(GameConfigurationgc:availableGames){
System.out.println(gc);
}
}
}
/*
*GameManager.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.main.GameConfigurationParser;
importbr.ufsc.inf.lagar.utils.RTSI;
importjava.io.InputStream;
importjava.util.ArrayList;
importjava.util.List;
publicclassGameManager{
privatestaticList<GameConfiguration>availableGames=null;
privatestaticGameConfigurationcurrentGame=null;
170
/**
*CreatesanewinstanceofGameManager
*/
privateGameManager(){
privatestaticvoidloadGames(){
GameManager.availableGames=newArrayList<GameConfiguration>();
StringpackageName="/gametypes";
List<String>xmls=RTSI.findFiles(packageName,"xml");
GameConfigurationParsergcp=newGameConfigurationParser();
for(Stringxml:xmls){
try{
if(!xml.startsWith("/")){
xml="/"+xml;
}
if(!xml.startsWith(packageName)){
xml=packageName+"/"+xml;
}
System.out.println(xml);
InputStreamin=GameManager.class.getResourceAsStream(xml);
System.out.println(in);
GameConfigurationgc=gcp.parse(in);
GameManager.availableGames.add(gc);
}catch(Exceptionex){
thrownewRuntimeException("Erroringamefactoryloadgames",ex);
}
}
}
publicstaticList<GameConfiguration>getAvailableGames(){
if(GameManager.availableGames==null){
loadGames();
}
returnavailableGames;
}
publicstaticvoidsetCurrentGame(GameConfigurationaCurrentGame){
currentGame=aCurrentGame;
}
publicstaticvoidsetCurrentGame(StringgameName){
for(GameConfigurationgc:availableGames){
if(gc.getName().equals(gameName)){
currentGame=gc;
break;
}
}
if(currentGame==null)
thrownewIllegalArgumentException(gameName+"isnotavalidgameName");
}
171
publicstaticGameConfigurationgetCurrentGame(){
returncurrentGame;
}
}
/*
*GameResultIterator.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importjava.util.Iterator;
importjava.util.List;
publicclassGameResultIteratorimplementsGameCardIterator{
privateGameResultsgr;
privateList<GameCard>games;
privateintposition;
/**
*CreatesanewinstanceofGameResultIterator
*/
publicGameResultIterator(GameResultsgr,intbegin,intend,intjump){
this.gr=gr;
this.games=gr.getSubset(begin,end,jump);
}
publicbooleanhasNext(){
returnposition<this.games.size();
}
publicGameCardnext(){
GameCardgc=this.games.get(position);
++position;
returngc;
}
publicvoidnext(GameCardcardBuffer){
GameCardnext=this.next();
cardBuffer.setDate(next.getDate());
172
cardBuffer.setSerial(next.getSerial());
cardBuffer.setBalls(next.getBalls());
}
publiclongsize(){
returnthis.games.size();
}
publicvoidremove(){
thrownewUnsupportedOperationException("Notallowedtoremove");
}
publicintgetBallsPerCard(){
returnthis.games.get(0).getBalls().length;
}
publicvoidclose(){
}
}
/*
*GameResults.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.resultloader.ResultLoader;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
publicclassGameResults{
privateResultLoaderresultLoader;
privateList<GameCard>loadedResults=newArrayList<GameCard>();
/**CreatesanewinstanceofGameResults*/
publicGameResults(){
}
publicResultLoadergetResultLoader(){
returnresultLoader;
}
173
publicvoidsetResultLoader(ResultLoaderresultLoader){
this.resultLoader=resultLoader;
}
publicList<GameCard>getLoadedResults(){
returnloadedResults;
}
publicvoidloadResults()throwsIOException{
this.loadedResults=this.resultLoader.loadResults();
Collections.sort(this.loadedResults);
}
publicList<GameCard>getSubset(intbegin,intend,intjump){
//specialcase:allresults
if(begin==1&&end==this.loadedResults.get(this.loadedResults.size()
1).serial&&jump==1){
returnthis.loadedResults;
}
ArrayList<GameCard>subset=newArrayList<GameCard>();
for(inti=begin1;i<end;i+=jump){
subset.add(this.loadedResults.get(i));
}
returnsubset;
}
}
/*
*GenCardIO.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.generator;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameCardIterator;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importjava.io.DataInputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
174
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipInputStream;
publicclassGenCardIOimplementsGameCardIterator{
privateDataInputStreamdis;
privateGeneratorHeadergeneratorHeader;
privatelonglastCardRead;
/**
*CreatesanewinstanceofGenCardIO
*/
publicGenCardIO(FilellgFile)throwsIOException{
this.generatorHeader=GeneratorHeader.fetchGeneratorHeader(llgFile);
this.dis=this.openGeneratedCardsStream(llgFile);
}
publicbooleanskipToCard(GameCardcardBuffer,longcardNumber)throws
IOException{
if(cardNumber<=this.lastCardRead){
//thrownewIllegalArgumentException("cardNumbermustbegreaterthan
lastCardRead");
returnfalse;
}
longalreadySkip=this.lastCardRead*
this.generatorHeader.getBallsPerCard();
this.lastCardRead=cardNumber1;
longbytesToSkip=(cardNumber1)*this.generatorHeader.getBallsPerCard();
bytesToSkip=bytesToSkipalreadySkip;
while(bytesToSkip!=0){
longn=this.dis.skip(bytesToSkip);
bytesToSkip=n;
}
this.next(cardBuffer);
returntrue;
}
publicvoidclose(){
try{
this.dis.close();
}catch(IOExceptionex){
ex.printStackTrace();
}
}
privateDataInputStreamopenGeneratedCardsStream(FilellgFile)throws
IOException{
FileInputStreamfin=newFileInputStream(llgFile);
ZipInputStreamzin=newZipInputStream(fin);
DataInputStreamdis=newDataInputStream(zin);
ZipEntrye=null;
175
while((e=zin.getNextEntry())!=null){
if(e.getName().equals(LagarLotteryGlobals.GENERATED_CARDS_NAME)){
break;
}
}
if(e==null)thrownewIOException("Nogeneratedcardsfound.");
returndis;
}
publiclongsize(){
returnthis.generatorHeader.getNumberOfCards();
}
publicbooleanhasNext(){
returnthis.lastCardRead<this.size();
}
publicGameCardnext(){
GameCardg=newGameCard(0,null,this.getBallsPerCard());
this.next(g);
returng;
}
publicvoidremove(){
thrownewUnsupportedOperationException("Notallowedtoremove");
}
publicvoidnext(GameCardcardBuffer){
++lastCardRead;
if(cardBuffer.getBalls()==null){
cardBuffer.setBalls(newbyte[this.getBallsPerCard()]);
}
try{
this.dis.readFully(cardBuffer.getBalls());
cardBuffer.setSerial((int)lastCardRead);
}catch(IOExceptionex){
thrownewRuntimeException(ex);
}
publicintgetBallsPerCard(){
returnthis.generatorHeader.getBallsPerCard();
}
}
/*
*GenerateBallPositions.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
176
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.utils;
importjava.text.NumberFormat;
importjava.util.Locale;
importjava.util.regex.Matcher;
publicclassGenerateBallPositions{
/**CreatesanewinstanceofGenerateBallPositions*/
publicGenerateBallPositions(){
}
publicvoidgeneratePositions(intfirstBall,intlastBall,intendLine,double
xStart,
doubleyStart,doublexInc,doubleyInc){
NumberFormatf=NumberFormat.getNumberInstance(Locale.US);
f.setMaximumFractionDigits(2);
Strings="<balln=\"?\"x=\"?\"y=\"?\"/>";
doublestartY=yStart;
intm=0;
for(inti=firstBall;i<=lastBall;++i){
Stringc=s.replaceFirst("\\?",String.valueOf(i));
doubleincX=xStart+(xInc*m);
c=c.replaceFirst("\\?",f.format(incX));
c=c.replaceFirst("\\?",f.format(startY));
System.out.println(c);
if(++m%10==0){
m=0;
startY=yStart+(yInc*(i/10));
}
}
}
publicstaticvoidmain(String[]args){
newGenerateBallPositions().generatePositions(
1,80,10,1.2,5.82,0.65,0.325);
}
}
/*
*GeneratorAllCombPanel.java
177
*
*Createdon28deFevereirode2007,19:42
*/
packagebr.ufsc.inf.lagar.generator.impl;
importbr.ufsc.inf.lagar.generator.GeneratorInterface;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.generator.AllCombinationGeneratorService;
importbr.ufsc.inf.lagar.ui.dialog.ProgressDialog;
importbr.ufsc.inf.lagar.ui.panels.*;
importjava.awt.Color;
importjava.io.IOException;
importjava.text.NumberFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjavax.swing.JFileChooser;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.SwingUtilities;
importorg.apache.commons.lang.StringUtils;
/**
*
*@authorlagar
*/
publicclassGeneratorAllCombPanelextendsjavax.swing.JPanelimplements
GeneratorInterface{
/**
*CreatesnewformGeneratorAllCombPanel
*/
publicGeneratorAllCombPanel(){
initComponents();
this.setNumbersAreaEnabled(false);
GameConfigurationgc=GameManager.getCurrentGame();
for(inti=gc.getMinNumbersToChoose();i<=gc.getMaxNumbersToChoose();
++i){
this.numbersPerCardCombo.addItem(i);
}
this.fileChooserLLG1.setMode(FileChooserLLG.ChooserMode.SAVE_MODE);
privatevoidsetNumbersAreaEnabled(booleanenabled){
if(enabled){
this.numbersArea.setBackground(Color.WHITE);
}
else{
this.numbersArea.setBackground(this.getBackground());
}
this.numbersArea.setEditable(enabled);
}
privatevoidgenerateCards(){
try{
178
int[]numbers=null;
if(this.allPossibleRadio.isSelected()){
intmaxNumbers=GameManager.getCurrentGame().getNumbersPerCard();
numbers=newint[maxNumbers];
for(inti=0;i<numbers.length;++i){
numbers[i]=i+1;
}
}
else{
numbers=this.parseUserNumbers(this.numbersArea.getText());
if(numbers.length<
(Integer)this.numbersPerCardCombo.getSelectedItem()){
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("You_typed_few_numbers"),
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
StringBuildersb=newStringBuilder();
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("You_typed_the_numbers_below"));
sb.append("\n");
NumberFormatnf=NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(2);
for(inti=0;i<numbers.length;++i){
sb.append(nf.format(numbers[i]));
sb.append("");
if((i+1)%10==0){
sb.delete(sb.length()3,sb.length());
sb.append("\n");
}
}
if(sb.charAt(sb.length()1)==''){
sb.delete(sb.length()3,sb.length());
sb.append("\n");
}
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("Is_it_correct?"));
if(JOptionPane.showConfirmDialog(null,sb.toString())!=
JOptionPane.YES_OPTION){
return;
}
finalAllCombinationGeneratorServiceservice=new
AllCombinationGeneratorService(
this.fileChooserLLG1.getFilePath().trim(),
numbers,
(Integer)this.numbersPerCardCombo.getSelectedItem());
finalProgressDialogpd=newProgressDialog(null,true,service);
pd.setLocationRelativeTo(null);
179
Threadt=newThread(newRunnable(){
publicvoidrun(){
try{
service.generateAllCombinations();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("Cards_generated_successfully"),
java.util.ResourceBundle.getBundle("resources/bundles/lag
arLottery").getString("Ok"),
JOptionPane.INFORMATION_MESSAGE);
}catch(IOExceptionex){
ex.printStackTrace();
}
finally{
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
pd.exit();
}
});
}
}
});
t.start();
pd.showProgressDialog();
}catch(NumberFormatExceptionex){
ex.printStackTrace();
}catch(IOExceptionex){
ex.printStackTrace();
}catch(IllegalArgumentExceptioniaex){
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
_parsing_numbers._Make_sure_your_numbers_are_typed_correctly,_are_inside_the_valid_ra
nge_area_and_try_again."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
}
privateint[]parseUserNumbers(StringuserData)throwsIllegalArgumentException{
StringBuildersb=newStringBuilder(userData);
intindex=sb.indexOf("\n");
while(index!=1){
sb.replace(index,index+1,"");
index=sb.indexOf("\n");
}
intminNumber=1;
intmaxNumber=GameManager.getCurrentGame().getNumbersPerCard();
String[]parts=sb.toString().trim().split("");
ArrayList<Integer>numbers=newArrayList(parts.length);
for(inti=0;i<parts.length;++i){
Strings=StringUtils.deleteWhitespace(parts[i]);
try{
if(s==null||s.equals(""))continue;
180
Integern=Integer.valueOf(s);
if(numbers.contains(n))continue;
numbers.add(n);
if(n>maxNumber||n<minNumber){
thrownewIllegalArgumentException();
}
}
catch(Exceptionex){
thrownewIllegalArgumentException(ex);
}
int[]nums=newint[numbers.size()];
for(inti=0;i<nums.length;++i){
nums[i]=numbers.get(i);
}
Arrays.sort(nums);
returnnums;
}
privatebooleanvalidaForm(){
StringBuildererrors=newStringBuilder();
if(this.numbersRadio.isSelected()){
if(this.numbersArea.getText().equals("")){
errors.append(java.util.ResourceBundle.getBundle("resources/bundles/l
agarLottery").getString("_You_must_type_the_numbers."));
errors.append("\n");
}
}
Stringfile=this.fileChooserLLG1.getFilePath();
if(file==null||file.equals("")){
errors.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("_You_must_choose_a_file_to_save."));
errors.append("\n");
}
if(errors.length()!=0){
JOptionPane.showMessageDialog(
null,errors.toString(),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
"),JOptionPane.ERROR_MESSAGE);
returnfalse;
}
returntrue;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
181
BEGIN:initComponents
privatevoidinitComponents(){
radioGroup=newjavax.swing.ButtonGroup();
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
topPanel=newjavax.swing.JPanel();
textLabel=newjavax.swing.JLabel();
numbersPanel=newjavax.swing.JPanel();
allPossibleRadio=newjavax.swing.JRadioButton();
numbersRadio=newjavax.swing.JRadioButton();
jScrollPane1=newjavax.swing.JScrollPane();
numbersArea=newjavax.swing.JTextArea();
numbersPerCardLabel=newjavax.swing.JLabel();
numbersPerCardCombo=newjavax.swing.JComboBox();
hintLabel=newjavax.swing.JLabel();
filePanel=newjavax.swing.JPanel();
fileChooserLLG1=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
bottomPanel=newjavax.swing.JPanel();
generateButton=newjavax.swing.JButton();
jLabel4=newjavax.swing.JLabel();
jLabel5=newjavax.swing.JLabel();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
simpleInternalFrame1.setTitle(bundle.getString("Generators"));//NOI18N
textLabel.setText(bundle.getString("This_module_generates_all_combinations"))
;//NOI18N
org.jdesktop.layout.GroupLayouttopPanelLayout=new
org.jdesktop.layout.GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(
topPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADIN
G)
.add(topPanelLayout.createSequentialGroup()
.addContainerGap()
.add(textLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,481,
Short.MAX_VALUE)
.addContainerGap())
);
topPanelLayout.setVerticalGroup(
topPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADIN
G)
.add(textLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,76,
Short.MAX_VALUE)
);
numbersPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.ge
tString("Numbers")));//NOI18N
radioGroup.add(allPossibleRadio);
allPossibleRadio.setSelected(true);
allPossibleRadio.setText(bundle.getString("Generate_all_possible_combinations
_(all_numbers)"));//NOI18N
allPossibleRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,
0,0));
allPossibleRadio.setMargin(newjava.awt.Insets(0,0,0,0));
allPossibleRadio.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
allPossibleRadioActionPerformed(evt);
}
});
radioGroup.add(numbersRadio);
182
numbersRadio.setText(bundle.getString("Generate_cards_only_with_the_numbers_b
elow:"));//NOI18N
numbersRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,
0));
numbersRadio.setMargin(newjava.awt.Insets(0,0,0,0));
numbersRadio.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
numbersRadioActionPerformed(evt);
}
});
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HOR
IZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTI
CAL_SCROLLBAR_ALWAYS);
numbersArea.setColumns(20);
numbersArea.setLineWrap(true);
numbersArea.setRows(5);
numbersArea.setWrapStyleWord(true);
jScrollPane1.setViewportView(numbersArea);
numbersPerCardLabel.setText(bundle.getString("Numbers_per_card:"));//NOI18N
hintLabel.setForeground(newjava.awt.Color(153,153,153));
hintLabel.setText(bundle.getString("<html>_Type_the_numbers_separated_by___'<
b></b>'____Ex:_1__2__3__4__5__6_</html>"));//NOI18N
org.jdesktop.layout.GroupLayoutnumbersPanelLayout=new
org.jdesktop.layout.GroupLayout(numbersPanel);
numbersPanel.setLayout(numbersPanelLayout);
numbersPanelLayout.setHorizontalGroup(
numbersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(numbersPanelLayout.createSequentialGroup()
.add(numbersPanelLayout.createParallelGroup(org.jdesktop.layout.Group
Layout.LEADING)
.add(numbersPanelLayout.createSequentialGroup()
.addContainerGap()
.add(numbersPanelLayout.createParallelGroup(org.jdesktop.layo
ut.GroupLayout.LEADING)
.add(allPossibleRadio)
.add(numbersRadio)))
.add(numbersPanelLayout.createSequentialGroup()
.addContainerGap()
.add(numbersPerCardLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(numbersPerCardCombo,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,72,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(numbersPanelLayout.createSequentialGroup()
.add(29,29,29)
.add(numbersPanelLayout.createParallelGroup(org.jdesktop.layo
ut.GroupLayout.LEADING)
.add(hintLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,454,Short.MAX_VALUE)
.add(jScrollPane1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,454,Short.MAX_VALUE))))
.addContainerGap())
);
numbersPanelLayout.setVerticalGroup(
numbersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(numbersPanelLayout.createSequentialGroup()
.add(numbersPanelLayout.createParallelGroup(org.jdesktop.layout.Group
183
Layout.BASELINE)
.add(numbersPerCardLabel)
.add(numbersPerCardCombo,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(allPossibleRadio)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(numbersRadio)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,90,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(hintLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,15,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
filePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Fileto
save"));
org.jdesktop.layout.GroupLayoutfilePanelLayout=new
org.jdesktop.layout.GroupLayout(filePanel);
filePanel.setLayout(filePanelLayout);
filePanelLayout.setHorizontalGroup(
filePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(filePanelLayout.createSequentialGroup()
.addContainerGap()
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
471,Short.MAX_VALUE)
.addContainerGap())
);
filePanelLayout.setVerticalGroup(
filePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(filePanelLayout.createSequentialGroup()
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
26,Short.MAX_VALUE)
.addContainerGap())
);
generateButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
generateButton.setText(bundle.getString("Generate"));//NOI18N
generateButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
generateButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutbottomPanelLayout=new
org.jdesktop.layout.GroupLayout(bottomPanel);
bottomPanel.setLayout(bottomPanelLayout);
bottomPanelLayout.setHorizontalGroup(
bottomPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
DING)
.add(bottomPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel4,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,174,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(generateButton)
184
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel5,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,174,
Short.MAX_VALUE)
.addContainerGap())
);
bottomPanelLayout.setVerticalGroup(
bottomPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
DING)
.add(jLabel4,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,23,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel5,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,23,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(generateButton)
);
bottomPanelLayout.linkSize(newjava.awt.Component[]{jLabel4,jLabel5},
org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(simpleInternalFrame1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
505,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,filePanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(bottomPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(topPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,numbersPanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(topPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(numbersPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filePanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(bottomPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}//</editorfold>//GENEND:initComponents
privatevoidnumbersRadioActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_numbersRadioActionPerformed
185
this.setNumbersAreaEnabled(true);
}//GENLAST:event_numbersRadioActionPerformed
privatevoidallPossibleRadioActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_allPossibleRadioActionPerformed
this.setNumbersAreaEnabled(false);
}//GENLAST:event_allPossibleRadioActionPerformed
privatevoidgenerateButtonActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_generateButtonActionPerformed
booleanok=this.validaForm();
if(ok)this.generateCards();
}//GENLAST:event_generateButtonActionPerformed
publicJPanelgetGeneratorPanel(){
returnthis;
}
publicStringgetGeneratorName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/generator/impl/generatorTr").ge
tString("All_combination_generator");
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JRadioButtonallPossibleRadio;
privatejavax.swing.JPanelbottomPanel;
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserLLG1;
privatejavax.swing.JPanelfilePanel;
privatejavax.swing.JButtongenerateButton;
privatejavax.swing.JLabelhintLabel;
privatejavax.swing.JLabeljLabel4;
privatejavax.swing.JLabeljLabel5;
privatejavax.swing.JScrollPanejScrollPane1;
privatejavax.swing.JTextAreanumbersArea;
privatejavax.swing.JPanelnumbersPanel;
privatejavax.swing.JComboBoxnumbersPerCardCombo;
privatejavax.swing.JLabelnumbersPerCardLabel;
privatejavax.swing.JRadioButtonnumbersRadio;
privatejavax.swing.ButtonGroupradioGroup;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
privatejavax.swing.JLabeltextLabel;
privatejavax.swing.JPaneltopPanel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*GeneratorHeader.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
186
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.generator;
importbr.ufsc.inf.lagar.main.LagarLotteryGlobals;
importjava.beans.XMLDecoder;
importjava.beans.XMLEncoder;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.Date;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipInputStream;
publicclassGeneratorHeader{
privateintversion;
privateStringgameName;
privatelongnumberOfCards;
privateintballsPerCard;
privateDatedate;
privateint[]numbers;
/**CreatesanewinstanceofGeneratorHeader*/
publicGeneratorHeader(){
this.setVersion(1);
this.setDate(newDate());
}
publicstaticGeneratorHeaderfetchGeneratorHeader(FilellgFile)throws
IOException{
FileInputStreamfin=newFileInputStream(llgFile);
ZipInputStreamzin=newZipInputStream(fin);
ZipEntrye=null;
while((e=zin.getNextEntry())!=null){
if(e.getName().equals(LagarLotteryGlobals.GENERATED_HEADER_NAME)){
break;
}
}
GeneratorHeaderheader=GeneratorHeader.loadFromStream(zin);
zin.closeEntry();
zin.close();
returnheader;
}
publicstaticGeneratorHeaderloadFromStream(InputStreamis)throwsIOException{
187
byte[]buff=newbyte[8192];
ByteArrayOutputStreambos=newByteArrayOutputStream(8192);
intn=0;
while((n=is.read(buff))>=0){
bos.write(buff,0,n);
}
ByteArrayInputStreambis=newByteArrayInputStream(bos.toByteArray());
XMLDecoderdecoder=newXMLDecoder(bis);
GeneratorHeaderheader=(GeneratorHeader)decoder.readObject();
decoder.close();
returnheader;
publicvoidsaveToStream(OutputStreamos)throwsIOException{
ByteArrayOutputStreamout=newByteArrayOutputStream();
XMLEncoderencoder=newXMLEncoder(out);
encoder.writeObject(this);
encoder.close();
os.write(out.toByteArray());
publicintgetVersion(){
returnversion;
}
publicvoidsetVersion(intversion){
this.version=version;
}
publicStringgetGameName(){
returngameName;
}
publicvoidsetGameName(StringgameName){
this.gameName=gameName;
}
publiclonggetNumberOfCards(){
returnnumberOfCards;
}
publicvoidsetNumberOfCards(longnumberOfCards){
this.numberOfCards=numberOfCards;
}
publicintgetBallsPerCard(){
returnballsPerCard;
}
publicvoidsetBallsPerCard(intballsPerCard){
this.ballsPerCard=ballsPerCard;
}
publicDategetDate(){
returndate;
188
}
publicvoidsetDate(Datedate){
this.date=date;
}
publicint[]getNumbers(){
returnnumbers;
}
publicvoidsetNumbers(int[]numbers){
this.numbers=numbers;
}
}
/*
*GeneratorInterface.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.generator;
importjavax.swing.JPanel;
/**
*
*@authorlagar
*/
publicinterfaceGeneratorInterface{
publicStringgetGeneratorName();
publicJPanelgetGeneratorPanel();
}
/*
*GeneratorMetaPanel.java
*
*Createdon18deAbrilde2007,22:18
*/
packagebr.ufsc.inf.lagar.ui.panels;
importjava.awt.CardLayout;
/**
*
189
*@authorlagar
*/
publicclassGeneratorMetaPanelextendsjavax.swing.JPanel{
privateGeneratorPanelgp;
/**CreatesnewformGeneratorMetaPanel*/
publicGeneratorMetaPanel(){
initComponents();
this.gp=newGeneratorPanel();
this.gp.setMetaPanel(this);
this.add(gp,gp.getClass().getName());
}
publicvoidloadAvailableGenerators()throwsException{
gp.loadAvailableGenerators();
}
publicvoidresetPanel(){
CardLayoutcardLayout=(CardLayout)this.getLayout();
cardLayout.show(this,gp.getClass().getName());
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
setLayout(newjava.awt.CardLayout());
}//</editorfold>//GENEND:initComponents
//Variablesdeclarationdonotmodify//GENBEGIN:variables
//Endofvariablesdeclaration//GENEND:variables
}
/*
*GeneratorPanel.java
*
*Createdon18deAbrilde2007,22:00
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.generator.GeneratorInterface;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.utils.RTSI;
importjava.awt.CardLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.ArrayList;
importjava.util.HashMap;
importjavax.swing.JPanel;
/**
*
*@authorlagar
190
*/
publicclassGeneratorPanelextendsjavax.swing.JPanelimplementsActionListener{
privateHashMap<String,GeneratorInterface>vs=newHashMap<String,
GeneratorInterface>();
privateStringselection;
privateJPanelmetaPanel;
/**CreatesnewformGeneratorPanel*/
publicGeneratorPanel(){
initComponents();
}
publicvoidloadAvailableGenerators()throwsException{
GameConfigurationcurrent=GameManager.getCurrentGame();
StringpackageName="br.ufsc.inf.lagar.generator.impl";
booleanfirst=true;
ArrayList<String>classes=RTSI.find(packageName,GeneratorInterface.class);
for(Stringclazz:classes){
clazz=packageName+"."+clazz;
GeneratorInterfacegenerator=(GeneratorInterface)
Class.forName(clazz).newInstance();
this.vs.put(generator.getGeneratorName(),generator);
RadioPanelrp=newRadioPanel();
rp.getRadioButton().setText(generator.getGeneratorName());
rp.getRadioButton().setActionCommand(generator.getGeneratorName());
rp.getRadioButton().addActionListener(this);
this.buttonGroup1.add(rp.getRadioButton());
this.versPanel.add(rp);
this.metaPanel.add(generator.getGeneratorPanel(),
generator.getGeneratorName());
if(first){
rp.getRadioButton().setSelected(true);
first=false;
this.selection=generator.getGeneratorName();
}
this.jScrollPane1.revalidate();
this.repaint();
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
191
buttonGroup1=newjavax.swing.ButtonGroup();
jPanel1=newjavax.swing.JPanel();
jLabel1=newjavax.swing.JLabel();
jScrollPane1=newjavax.swing.JScrollPane();
versPanel=newjavax.swing.JPanel();
labelSepLeft=newjavax.swing.JLabel();
openButton=newjavax.swing.JButton();
labelSepRight=newjavax.swing.JLabel();
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
jLabel1.setText(bundle.getString("choose_one_generator_available"));//
NOI18N
org.jdesktop.layout.GroupLayoutjPanel1Layout=new
org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,482,
Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,43,
Short.MAX_VALUE)
.addContainerGap())
);
jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.ge
tString("Generators")));//NOI18N
versPanel.setLayout(newjavax.swing.BoxLayout(versPanel,
javax.swing.BoxLayout.Y_AXIS));
jScrollPane1.setViewportView(versPanel);
openButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
openButton.setText(bundle.getString("Open"));//NOI18N
openButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
openButtonActionPerformed(evt);
}
});
simpleInternalFrame1.setTitle(bundle.getString("Generators"));//NOI18N
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(labelSepLeft,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,198,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
192
.add(openButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(labelSepRight,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
198,Short.MAX_VALUE))
.add(simpleInternalFrame1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
506,Short.MAX_VALUE)
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,506,
Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,175,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(labelSepLeft,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(openButton)
.add(labelSepRight,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.linkSize(newjava.awt.Component[]{labelSepLeft,labelSepRight},
org.jdesktop.layout.GroupLayout.VERTICAL);
}//</editorfold>//GENEND:initComponents
privatevoidopenButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_openButtonActionPerformed
CardLayoutcardLayout=(CardLayout)this.metaPanel.getLayout();
cardLayout.show(this.metaPanel,this.selection);
}//GENLAST:event_openButtonActionPerformed
publicvoidactionPerformed(ActionEvente){
this.selection=e.getActionCommand();
}
publicJPanelgetMetaPanel(){
returnmetaPanel;
}
publicvoidsetMetaPanel(JPanelmetaPanel){
this.metaPanel=metaPanel;
}
193
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.ButtonGroupbuttonGroup1;
privatejavax.swing.JLabeljLabel1;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JScrollPanejScrollPane1;
privatejavax.swing.JLabellabelSepLeft;
privatejavax.swing.JLabellabelSepRight;
privatejavax.swing.JButtonopenButton;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
privatejavax.swing.JPanelversPanel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*IWizardPage.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui.wizard;
publicinterfaceIWizardPage{
publicvoidsetWizardPanel(WizardPanelwizardPanel);
publicvoidactivatePage();
publicvoiddeactivatePage();
publicStringgetPageName();
publicStringgetNextPageName();
}
/*
*JTableTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
194
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importjava.awt.Color;
importjava.awt.Component;
importjava.awt.Dimension;
importjava.awt.Frame;
importjava.util.Enumeration;
importjavax.swing.JDialog;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JScrollPane;
importjavax.swing.JTable;
importjavax.swing.SwingConstants;
importjavax.swing.event.TableModelListener;
importjavax.swing.table.TableCellRenderer;
importjavax.swing.table.TableColumn;
importjavax.swing.table.TableModel;
importjunit.framework.TestCase;
publicclassJTableTestextendsTestCaseimplementsTableModel{
privateCellDataone=newCellData("AB",Color.GREEN);
privateCellDatatwo=newCellData("CD",Color.RED);
/**
*CreatesanewinstanceofJTableTest
*/
publicJTableTest(){
publicintgetRowCount(){
return500;
}
publicintgetColumnCount(){
return22;
}
publicStringgetColumnName(intcolumnIndex){
returnString.valueOf(columnIndex);
}
publicClass<?>getColumnClass(intcolumnIndex){
returnCellData.class;
}
publicbooleanisCellEditable(introwIndex,intcolumnIndex){
returnfalse;
}
publicObjectgetValueAt(introwIndex,intcolumnIndex){
if(rowIndex==columnIndex){
returnthis.one;
}
195
returnthis.two;
}
publicvoidsetValueAt(ObjectaValue,introwIndex,intcolumnIndex){
}
publicvoidaddTableModelListener(TableModelListenerl){
}
publicvoidremoveTableModelListener(TableModelListenerl){
}
publicvoidtestTable(){
DecisionDialogd=newDecisionDialog(null,true);
JTabletable=newJTable(newJTableTest());
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(CellData.class,newCellDataRenderer());
//table.setPreferredScrollableViewportSize(newDimension(20,20));
//table.createDefaultColumnsFromModel();
Enumeration<TableColumn>columns=table.getColumnModel().getColumns();
while(columns.hasMoreElements()){
TableColumnt=columns.nextElement();
t.setMinWidth(30);
t.setPreferredWidth(30);
//t.setResizable(false);
}
JScrollPanepane=newJScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS
_NEEDED);
d.getMainPanel().add(pane,"table");
d.pack();
d.setVisible(true);
}
}
classCellData{
privateStringtext;
privateColorcolor;
publicCellData(){
publicCellData(Stringtext,Colorc){
this.text=text;
this.color=c;
}
publicStringgetText(){
returntext;
}
publicvoidsetText(Stringtext){
196
this.text=text;
}
publicColorgetColor(){
returncolor;
}
publicvoidsetColor(Colorc){
this.color=c;
}
classCellDataRendererextendsJLabelimplementsTableCellRenderer{
publicCellDataRenderer(){
this.setOpaque(true);
this.setHorizontalAlignment(SwingConstants.CENTER);
}
publicComponentgetTableCellRendererComponent(JTabletable,Objectvalue,
booleanisSelected,booleanhasFocus,introw,intcolumn){
CellDatac=(CellData)value;
if(!isSelected)this.setBackground(c.getColor());
else{
Colorcol=c.getColor();
this.setBackground(col.darker());
}
this.setText(c.getText());
returnthis;
}
}
/*
*LagarLotteryGlobals.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
publicclassLagarLotteryGlobals{
publicstaticfinalStringGENERATED_HEADER_NAME="gheader";
publicstaticfinalStringGENERATED_CARDS_NAME="cards";
197
publicstaticfinalStringGENERATED_FILTER_NAME="filters";
publicstaticfinalStringLL_HOME=
System.getProperty("user.home")+"/.lagarLottery";
}
/*
*LineAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.DefaultTableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Color;
importjava.lang.reflect.InvocationTargetException;
importjava.text.DecimalFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjavax.swing.JOptionPane;
importjavax.swing.SwingUtilities;
importorg.jfree.chart.ChartFactory;
importorg.jfree.chart.JFreeChart;
importorg.jfree.chart.labels.PieSectionLabelGenerator;
importorg.jfree.chart.labels.StandardPieSectionLabelGenerator;
importorg.jfree.chart.plot.MultiplePiePlot;
importorg.jfree.chart.plot.PiePlot;
importorg.jfree.data.category.DefaultCategoryDataset;
importorg.jfree.data.general.DefaultPieDataset;
importorg.jfree.util.TableOrder;
publicclassLineAnalysisextendsDefaultTableChartAnalysis{
privateStringinput=null;
privateList<String>cats;
privateMap<String,int[]>mChartData=newHashMap<String,int[]>();
/**CreatesanewinstanceofLineAnalysis*/
publicLineAnalysis(){
}
198
protectedvoidfillTableChart(){
intlines=Integer.valueOf(this.input);
intnumDrawn=getCurrentGameConfiguration().getNumbersPerDrawing();
intmaxCat=numDrawn>lines?lines:numDrawn;
for(Stringcat:cats){
this.mChartData.put(cat,newint[maxCat+1]);
}
GameCardcardBuffer=newGameCard();
int[]catsCount=newint[this.cats.size()];
for(intindex=0;this.gci.hasNext();++index){
this.gci.next(cardBuffer);
byte[]balls=cardBuffer.getBalls();
for(inti=0;i<balls.length;++i){
intball=balls[i];
intcat=(ball1)/lines;
++catsCount[cat];//incrementsumonthecolumn
}
for(intj=0;j<catsCount.length;++j){
Stringcategory=this.cats.get(j);
this.tcols.get(category)[index]=this.getHitz(catsCount[j]);
++this.mChartData.get(category)[catsCount[j]];//incrementsumof
category
}
this.tcols.get(this.columnOne)[index]=new
CellData(String.valueOf(cardBuffer.getSerial()),null,Color.BLACK,false);
Arrays.fill(catsCount,0);
//Integerdc=this.dataChart.get(category);
//this.dataChart.put(category,++dc);
}
protectedList<String>buildCategories(){
List<String>result=newArrayList<String>();
this.fetchNumberOfLines();
finalintlinesOrig=Integer.valueOf(this.input.trim());
intlines=linesOrig;
intnumbers=getCurrentGameConfiguration().getNumbersPerCard();
intfirst=1;
while(numbers>0){
Stringcat=null;
if(numbers>=linesOrig){
cat=String.valueOf(first)+""+lines;
result.add(cat);
}
else{
lines=numbers;
cat=String.valueOf(first)+""+lines;
result.add(cat);
199
break;
}
first+=linesOrig;
numbers=linesOrig;
lines+=linesOrig;
}
this.cats=result;
returnresult;
}
publicStringgetName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Line_analysis");
}
publicStringgetHelpInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Line_analysis_help_info");
}
publicJFreeChartgetChart(){
DefaultCategoryDatasetdataset=newDefaultCategoryDataset();
for(Stringkey:this.cats){
int[]rows=this.mChartData.get(key);
for(inti=0;i<rows.length;++i){
dataset.setValue(rows[i],Integer.valueOf(i),key);
}
}
JFreeChartchart=ChartFactory.createMultiplePieChart(this.getName(),
dataset,TableOrder.BY_COLUMN,true,true,false);
MultiplePiePlotplot=(MultiplePiePlot)chart.getPlot();
PiePlotpiePlot=(PiePlot)plot.getPieChart().getPlot();
PieSectionLabelGeneratorgenerator=newStandardPieSectionLabelGenerator(
"{0}{2}",newDecimalFormat("0"),newDecimalFormat("0.00%")
);
piePlot.setLabelGenerator(generator);
returnchart;
}
privatevoidfetchNumberOfLines(){
Runnabler=newRunnable(){
publicvoidrun(){
Strings=JOptionPane.showInputDialog(
null,
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gamean
alysis/analysisTr").getString("Enter_the_number_of_balls_per_line"),
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gamean
alysis/analysisTr").getString("Input"),
JOptionPane.QUESTION_MESSAGE);
if(s!=null&&!s.equals("")){
LineAnalysis.this.input=s;
}
else{
LineAnalysis.this.input=
String.valueOf(getCurrentGameConfiguration().getNumbersPerLine());
200
}
}
};
if(SwingUtilities.isEventDispatchThread()){
r.run();
}
else{
try{
SwingUtilities.invokeAndWait(r);
}catch(InterruptedExceptionex){
ex.printStackTrace();
}catch(InvocationTargetExceptionex){
ex.printStackTrace();
}
}
}
packagebr.ufsc.inf.lagar.utils;
importjava.io.IOException;
importjava.io.InputStream;
importorg.xml.sax.EntityResolver;
importorg.xml.sax.InputSource;
importorg.xml.sax.SAXException;
/**
*ThisSAXEntityResolverallowsustovalidateagainstlocalDTDs.
*
*publicstaticfinalStringDSML_DTD_PUBLIC_ID="http://www.dsml.org/DSML";
*publicstaticfinalStringDSML_DTD_RESOURCE=
"/net/socialchange/bob/dtds/dsml.dtd";
*..
*..
*builder.setEntityResolver(newLocalEntityResolver(DSML_DTD_PUBLIC_ID,
DSML_DTD_RESOURCE));
*..
*SAXBuilderbuilder=newSAXBuilder(true);
*
*
*Stolenfromjakartatomcat3.2.2,share/org/apache/jasper/compiler/JspUtil.java
*/
publicclassLocalEntityResolverimplementsEntityResolver{
StringdtdId;
StringdtdResource;
publicLocalEntityResolver(Stringid,Stringresource){
this.dtdId=id;
this.dtdResource=resource;
}
publicInputSourceresolveEntity(StringpublicId,StringsystemId)
throwsSAXException,IOException
{
System.out.println("publicId="+publicId);
System.out.println("systemIdis"+systemId);
System.out.println("resourceis"+dtdResource);
if(publicId==null){returnnull;}
201
if(publicId.equals(dtdId)){
InputStreaminput=
this.getClass().getResourceAsStream(dtdResource);
InputSourceisrc=
newInputSource(input);
returnisrc;
}
else{
System.out.println("returningnull");
returnnull;
}
}
}
/*
*LotofacilLoader.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.resultloader;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.io.IOException;
importjava.io.InputStream;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
importorg.htmlparser.Node;
importorg.htmlparser.Parser;
importorg.htmlparser.util.NodeList;
importorg.htmlparser.util.ParserException;
importorg.htmlparser.visitors.TagFindingVisitor;
publicclassLotofacilLoaderextendsCaixaLoader{
/**CreatesanewinstanceofLotofacilLoader*/
publicLotofacilLoader(){
//try{
//this.resultPath=new
URL("http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_quina.zip");
//this.resultPath=getClass().getResource("/D_lotfac.zip");
//}catch(MalformedURLExceptionex){
//ex.printStackTrace();
//}
}
202
publicList<GameCard>loadResults()throwsIOException{
List<GameCard>lotofacilResults=newArrayList<GameCard>();
SimpleDateFormatsdf=newSimpleDateFormat("dd/MM/yyyy");
InputStreamin=this.getHtmlStream();
byte[]buf=newbyte[1024];
StringBuildersb=newStringBuilder(300);
intlen=0;
while((len=in.read(buf))>0){
Strings=newString(buf,0,len);
sb.append(s);
}
in.close();
try{
Parserparser=newParser(sb.toString());
sb=null;
String[]tagsToBeFound={"TR"};
TagFindingVisitorvisitor=newTagFindingVisitor(tagsToBeFound);
parser.visitAllNodesWith(visitor);
//Firsttagspecifiedinsearch
Node[]trTags=visitor.getTags(0);
for(inti=1;i<trTags.length;++i){
Noden=trTags[i];
NodeListnl=n.getChildren();
GameCardr=newGameCard(1,null,15);
Nodeserial=nl.elementAt(1);
r.setSerial(Integer.parseInt(serial.getChildren().toHtml()));
Nodedate=nl.elementAt(3);
try{
r.setDate(sdf.parse(date.getChildren().toHtml()));
}catch(ParseExceptionex){
thrownewIOException("Errorparsingdateinresultxml");
}
intindex=0;
for(intj=5;j<=33;j+=2){
Nodeball=nl.elementAt(j);
r.setBall((byte)Integer.parseInt(ball.getChildren().toHtml()),
index);
++index;
}
Arrays.sort(r.getBalls());
lotofacilResults.add(r);
}
}catch(ParserExceptionex){
ex.printStackTrace();
}
returnlotofacilResults;
203
}
}
/*
*LotofacilLoaderTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.persistence.rs;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.resultloader.LotofacilLoader;
importbr.ufsc.inf.lagar.resultloader.ResultLoader;
importjava.io.IOException;
importjava.util.List;
importjunit.framework.*;
importjava.net.URL;
/**
*
*@authorlagar
*/
publicclassLotofacilLoaderTestextendsTestCase{
publicvoidtestLotofacilLoader()throwsIOException{
ResultLoaderloader=newLotofacilLoader();
List<GameCard>lotofacilResults=loader.loadResults();
for(GameCardd:lotofacilResults){
System.out.println(d);
}
}
}
/*
*LowHighAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
204
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.DefaultTableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Color;
importjava.util.ArrayList;
importjava.util.List;
publicclassLowHighAnalysisextendsDefaultTableChartAnalysis{
/**CreatesanewinstanceofLowHighAnalysis*/
publicLowHighAnalysis(){
}
protectedvoidfillTableChart(){
GameCardcardBuffer=newGameCard();
for(intindex=0;this.gci.hasNext();++index){
this.gci.next(cardBuffer);
byte[]balls=cardBuffer.getBalls();
intdivider=getCurrentGameConfiguration().getNumbersPerCard()/2;
intlows=0;
inthighs=0;
for(inti=0;i<balls.length;++i){
intball=balls[i];
if(ball<=divider)++lows;
else++highs;
}
Stringcategory=lows+""+highs;
this.tcols.get(category)[index]=this.hit;
this.tcols.get(this.columnOne)[index]=new
CellData(String.valueOf(cardBuffer.getSerial()),null,Color.BLACK,false);
Integerdc=this.dataChart.get(category);
this.dataChart.put(category,++dc);
}
publicStringgetName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Low_x_High_Analysis");
}
205
publicStringgetHelpInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Low_x_High_Analysis_Help_Info");
}
protectedList<String>buildCategories(){
List<String>result=newArrayList<String>();
intnumbersPerCard=getCurrentGameConfiguration().getNumbersPerCard();
intnumbersPerDraw=getCurrentGameConfiguration().getNumbersPerDrawing();
intnumLows=(numbersPerCard/2);
if(numLows<numbersPerDraw){
intnumHighs=numbersPerCardnumLows;
intfirstLow=numbersPerDrawnumHighs;
for(inti=firstLow;i<=numLows;++i){
Stringcat=i+""+(numbersPerDrawi);
result.add(cat);
}
}else{
for(inti=0;i<=numbersPerDraw;++i){
Stringcat=i+""+(numbersPerDrawi);
result.add(cat);
}
}
returnresult;
}
/*
*LowHighFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
importbr.ufsc.inf.lagar.filter.Filterable;
206
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameManager;
importorg.apache.commons.lang.StringUtils;
publicclassLowHighFilterextendsAbstractGameFilter{
privateString[]categs;
privateinthalf;
/**CreatesanewinstanceofLowHighFilter*/
publicLowHighFilter(){
this.half=GameManager.getCurrentGame().getNumbersPerCard()/2;
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
String[]params=input.split(Filterable.OR_SEPARATOR);
for(Strings:params){
String[]numbers=s.split("");
if(numbers.length!=2)thrownewTextInputFilterException();
for(Stringn:numbers){
try{
Integer.parseInt(n.trim());
}
catch(NumberFormatExceptionnfex){
thrownewTextInputFilterException(nfex);
}
}
this.categs=newString[params.length];
for(inti=0;i<categs.length;++i){
categs[i]=StringUtils.deleteWhitespace(params[i]);
}
}
publicStringgetShortName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Low_x_High");
}
publicStringgetFullName(){
returngetShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Low_x_High_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Low_x_High_help");
}
publicbooleanfilter(GameCardcard){
207
Stringcateg=this.getLowHighCategory(card);
for(Stringp:this.categs){
if(categ.equals(p)){
returnthis.isMode();
}
}
return!(this.isMode());
}
protectedStringgetLowHighCategory(GameCardcard){
intlows=0;
byte[]balls=card.getBalls();
for(byteb:balls){
if(b<=this.half){
++lows;
}
}
inthighs=balls.lengthlows;
returnlows+""+highs;
}
/*
*MainFrame.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importbr.ufsc.inf.lagar.ui.panels.AnalysisControlPanel;
importbr.ufsc.inf.lagar.ui.panels.FilterPanel;
importbr.ufsc.inf.lagar.ui.panels.GameChooserPanel;
importbr.ufsc.inf.lagar.generator.impl.GeneratorAllCombPanel;
importbr.ufsc.inf.lagar.ui.panels.GeneratorMetaPanel;
importbr.ufsc.inf.lagar.ui.panels.GeneratorPanel;
importbr.ufsc.inf.lagar.ui.panels.PrinterPanel;
importbr.ufsc.inf.lagar.ui.panels.UpdateDbPanel;
208
importbr.ufsc.inf.lagar.ui.panels.VerificatorPanel;
importjava.awt.CardLayout;
importjava.awt.Dimension;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.File;
importjava.io.IOException;
importjava.text.DateFormat;
importjava.text.NumberFormat;
importjava.util.List;
importjava.util.Locale;
importjavax.swing.JDialog;
importjavax.swing.JEditorPane;
importjavax.swing.JFrame;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.SwingUtilities;
importorg.apache.commons.lang.LocaleUtils;
/**
*
*@authorlagar
*/
publicclassMainFrameextendsjavax.swing.JFrame{
privatestaticfinalStringPROGRAM_NAME="lagarLottery1.0";
privateJPanelhomePanel=newJPanel();
privateAnalysisControlPanelanalysisPanel=null;
privateGeneratorMetaPanelgeneratorPanel=null;
privatePrinterPanelprinterPanel=null;
privateFilterPanelfilterPanel=null;
privateVerificatorPanelverificatorPanel=null;
/**CreatesnewformMainFrame*/
publicMainFrame(){
initComponents();
this.buttonBar.setBackground(this.getBackground());
this.setLocationRelativeTo(null);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
menuGroup=newjavax.swing.ButtonGroup();
jSplitPane=newjavax.swing.JSplitPane();
mainPanel=newjavax.swing.JPanel();
menuPane=newjavax.swing.JScrollPane();
buttonBar=newcom.l2fprod.common.swing.JButtonBar();
analysisButton=newjavax.swing.JToggleButton();
filterButton=newjavax.swing.JToggleButton();
generatorButton=newjavax.swing.JToggleButton();
printerButton=newjavax.swing.JToggleButton();
verificatorButton=newjavax.swing.JToggleButton();
statusPanel=newjavax.swing.JPanel();
209
menuBar=newjavax.swing.JMenuBar();
menuBarItem=newjavax.swing.JMenu();
listResMenuItem=newjavax.swing.JMenuItem();
updateResMenuItem=newjavax.swing.JMenuItem();
exitMenuItem=newjavax.swing.JMenuItem();
helpMenu=newjavax.swing.JMenu();
jMenuItem1=newjavax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSplitPane.setDividerLocation(115);
jSplitPane.setDividerSize(7);
jSplitPane.setOneTouchExpandable(true);
mainPanel.setLayout(newjava.awt.CardLayout());
mainPanel.setMinimumSize(newjava.awt.Dimension(300,300));
jSplitPane.setRightComponent(mainPanel);
menuPane.setBorder(null);
menuPane.setMinimumSize(newjava.awt.Dimension(115,22));
buttonBar.setBackground(newjava.awt.Color(238,238,238));
buttonBar.setPreferredSize(newjava.awt.Dimension(50,50));
menuGroup.add(analysisButton);
analysisButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/32x32/edu_mathematics.png"))
);
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
analysisButton.setText(bundle.getString("Analysis"));//NOI18N
analysisButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
analysisButtonActionPerformed(evt);
}
});
menuGroup.add(filterButton);
filterButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/32x32/filter.png")));
filterButton.setText(bundle.getString("Filters"));//NOI18N
filterButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
filterButtonActionPerformed(evt);
}
});
menuGroup.add(generatorButton);
generatorButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/32x32/gear.png")));
generatorButton.setText(bundle.getString("Generators"));//NOI18N
generatorButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
generatorButtonActionPerformed(evt);
}
});
menuGroup.add(printerButton);
printerButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/32x32/fileprint.png")));
printerButton.setText(bundle.getString("Print"));//NOI18N
printerButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
printerButtonActionPerformed(evt);
}
});
210
menuGroup.add(verificatorButton);
verificatorButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/32x32/button_ok.png")));
verificatorButton.setText(bundle.getString("Verificators"));//NOI18N
verificatorButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
verificatorButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutbuttonBarLayout=new
org.jdesktop.layout.GroupLayout(buttonBar);
buttonBar.setLayout(buttonBarLayout);
buttonBarLayout.setHorizontalGroup(
buttonBarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(buttonBarLayout.createSequentialGroup()
.addContainerGap()
.add(buttonBarLayout.createParallelGroup(org.jdesktop.layout.GroupLay
out.LEADING)
.add(generatorButton,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,86,Short.MAX_VALUE)
.add(filterButton,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
86,Short.MAX_VALUE)
.add(analysisButton,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,86,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,printerButton,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,86,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(verificatorButton,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,86,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
buttonBarLayout.linkSize(newjava.awt.Component[]{analysisButton,
filterButton,generatorButton},org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonBarLayout.setVerticalGroup(
buttonBarLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADI
NG)
.add(buttonBarLayout.createSequentialGroup()
.addContainerGap()
.add(analysisButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
56,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filterButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
56,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(generatorButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
66,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(printerButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
66,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(verificatorButton,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,66,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(77,Short.MAX_VALUE))
);
buttonBarLayout.linkSize(newjava.awt.Component[]{analysisButton,
filterButton,generatorButton},org.jdesktop.layout.GroupLayout.VERTICAL);
211
menuPane.setViewportView(buttonBar);
jSplitPane.setLeftComponent(menuPane);
org.jdesktop.layout.GroupLayoutstatusPanelLayout=new
org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
DING)
.add(0,640,Short.MAX_VALUE)
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEA
DING)
.add(0,20,Short.MAX_VALUE)
);
menuBarItem.setText(bundle.getString("Menu"));//NOI18N
listResMenuItem.setText(bundle.getString("List_results_DB"));//NOI18N
listResMenuItem.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
listResMenuItemActionPerformed(evt);
}
});
menuBarItem.add(listResMenuItem);
updateResMenuItem.setText(bundle.getString("Update_results_DB"));//NOI18N
updateResMenuItem.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
updateResMenuItemActionPerformed(evt);
}
});
menuBarItem.add(updateResMenuItem);
exitMenuItem.setText(bundle.getString("Exit"));//NOI18N
exitMenuItem.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
exitMenuItemActionPerformed(evt);
}
});
menuBarItem.add(exitMenuItem);
menuBar.add(menuBarItem);
helpMenu.setText(bundle.getString("About"));//NOI18N
jMenuItem1.setText(bundle.getString("About_item"));//NOI18N
jMenuItem1.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
jMenuItem1ActionPerformed(evt);
}
});
helpMenu.add(jMenuItem1);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
org.jdesktop.layout.GroupLayoutlayout=new
212
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jSplitPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,640,
Short.MAX_VALUE)
.add(statusPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(jSplitPane,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,433,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(statusPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
pack();
}//</editorfold>//GENEND:initComponents
privatevoidjMenuItem1ActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_jMenuItem1ActionPerformed
newAboutDialog(null,false).setVisible(true);
}//GENLAST:event_jMenuItem1ActionPerformed
privatevoidverificatorButtonActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_verificatorButtonActionPerformed
CardLayoutcardLayout=(CardLayout)this.mainPanel.getLayout();
cardLayout.show(this.mainPanel,VerificatorPanel.class.getName());
}//GENLAST:event_verificatorButtonActionPerformed
privatevoidlistResMenuItemActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_listResMenuItemActionPerformed
Threadt=newThread(newRunnable(){
publicvoidrun(){
List<GameCard>results=
GameManager.getCurrentGame().getGameResults().getLoadedResults();
JEditorPaneeditor=newJEditorPane("text/html","");
StringBuildersb=newStringBuilder();
DateFormatdf=DateFormat.getDateInstance(DateFormat.SHORT);
NumberFormatnf=NumberFormat.getIntegerInstance();
nf.setMinimumIntegerDigits(4);
NumberFormatnfb=NumberFormat.getIntegerInstance();
nfb.setMinimumIntegerDigits(2);
sb.append("<html>");
for(GameCardgc:results){
sb.append("<b>");
sb.append(nf.format(gc.getSerial()));
sb.append("</b>");
sb.append(":");
for(bytei:gc.getBalls()){
sb.append(nfb.format(i));
sb.append("");
}
sb.append("");
sb.append(df.format(gc.getDate()));
213
sb.append("<br>");
}
sb.append("</html>");
editor.setText(sb.toString());
JScrollPanescroll=newJScrollPane(editor,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
finalDecisionDialogdd=newDecisionDialog(MainFrame.this,false);
dd.getMainPanel().add(scroll,scroll.getClass().getName());
dd.getButtonsPanel().setVisible(false);
dd.getTitlePanel().setTitle(java.util.ResourceBundle.getBundle("resou
rces/bundles/lagarLottery").getString("Results_on_DB"));
Dimensiond=newDimension(700,400);
dd.setPreferredSize(d);
dd.setSize(d);
dd.setTitle("");
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
dd.setVisible(true);
}
});
}
});
t.start();
}//GENLAST:event_listResMenuItemActionPerformed
privatevoidexitMenuItemActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_exitMenuItemActionPerformed
this.exit();
}//GENLAST:event_exitMenuItemActionPerformed
privatevoidupdateResMenuItemActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_updateResMenuItemActionPerformed
this.loadResults(true);
this.analysisPanel.updateMaxCardsResultsDb(GameManager.getCurrentGame().getGa
meResults().getLoadedResults().size());
}//GENLAST:event_updateResMenuItemActionPerformed
privatevoidfilterButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_filterButtonActionPerformed
CardLayoutcardLayout=(CardLayout)this.mainPanel.getLayout();
cardLayout.show(this.mainPanel,FilterPanel.class.getName());
}//GENLAST:event_filterButtonActionPerformed
privatevoidprinterButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_printerButtonActionPerformed
CardLayoutcardLayout=(CardLayout)this.mainPanel.getLayout();
cardLayout.show(this.mainPanel,PrinterPanel.class.getName());
}//GENLAST:event_printerButtonActionPerformed
privatevoidgeneratorButtonActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_generatorButtonActionPerformed
214
this.generatorPanel.resetPanel();
CardLayoutcardLayout=(CardLayout)this.mainPanel.getLayout();
cardLayout.show(this.mainPanel,GeneratorMetaPanel.class.getName());
}//GENLAST:event_generatorButtonActionPerformed
privatevoidanalysisButtonActionPerformed(java.awt.event.ActionEventevt)
{//GENFIRST:event_analysisButtonActionPerformed
CardLayoutcardLayout=(CardLayout)this.mainPanel.getLayout();
cardLayout.show(this.mainPanel,AnalysisControlPanel.class.getName());
}//GENLAST:event_analysisButtonActionPerformed
publicvoidstartApp(){
List<GameConfiguration>games=GameManager.getAvailableGames();
GameChooserPanelpanel=newGameChooserPanel(games.size());
for(GameConfigurationgc:games){
panel.addOption(gc.getName());
}
Stringgame=null;
try{
game=panel.getSelectedGame();
}
catch(Exceptionex){
this.exit();
}
if(game==null){
this.exit();
}
GameManager.setCurrentGame(game);
this.setTitle(game+""+PROGRAM_NAME);
this.loadResults(false);
this.loadModules();
}
privatevoidexit(){
System.exit(0);
}
privatevoidloadResults(booleanonMainMenu){
try{
finalUpdateDbPanelupPanel=newUpdateDbPanel();
finalGameResultsgr=GameManager.getCurrentGame().getGameResults();
finalStringoriginalResultPath=gr.getResultLoader().getResultPath();
StringlocalPath=LagarLotteryGlobals.LL_HOME;
intpos=originalResultPath.lastIndexOf("/");
localPath=localPath+originalResultPath.substring(pos);
System.out.println(localPath);
FilelocalFile=newFile(localPath);
if(localFile.exists()){
gr.getResultLoader().setResultPath(localFile.toURI().toURL().toString
215
());
gr.loadResults();
gr.getResultLoader().setResultPath(originalResultPath);
if(!onMainMenu){
return;
}
List<GameCard>cards=gr.getLoadedResults();
DateFormatformat=DateFormat.getDateInstance(DateFormat.SHORT);
GameCardlast=cards.get(cards.size()1);
StringBuildersb=newStringBuilder();
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("<html>Your_results_database_ends_in_card:<br>"));
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("Number:_"));
sb.append(last.getSerial());
sb.append("<br>");
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("Date:_"));
sb.append(format.format(last.getDate()));
sb.append("<br>");
sb.append("<br>");
sb.append(java.util.ResourceBundle.getBundle("resources/bundles/lagar
Lottery").getString("Do_you_want_to_update_your_results_database?</html>"));
upPanel.getInfoLabel().setText(sb.toString());
}
else{
upPanel.getInfoLabel().setText(java.util.ResourceBundle.getBundle("res
ources/bundles/lagarLottery").getString("You_don't_have_a_local_results_database._Loa
d_from_the_web?"));
}
upPanel.getUrlField().setText(originalResultPath);
finalDecisionDialogdd=newDecisionDialog(this,true);
dd.getTitlePanel().setTitle(java.util.ResourceBundle.getBundle("resources
/bundles/lagarLottery").getString("Update_db?"));
dd.getMainPanel().add(upPanel,upPanel.getClass().getName());
ActionListenerl=newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(e.getActionCommand().equals(dd.getOkButton().getText())){
upPanel.getInfoLabel().setText(java.util.ResourceBundle.getBu
ndle("resources/bundles/lagarLottery").getString("Updating_results.._please_wait."));
dd.getOkButton().setEnabled(false);
dd.getCancelButton().setEnabled(false);
dd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
Threadt=newThread(newRunnable(){
publicvoidrun(){
try{
Stringweb=
upPanel.getUrlField().getText().trim();
if(!originalResultPath.equals(web)){
gr.getResultLoader().setResultPath(web);
}
gr.loadResults();
JOptionPane.showMessageDialog(
null,
216
java.util.ResourceBundle.getBundle("resources/bun
dles/lagarLottery").getString("Updated_successfully"),
java.util.ResourceBundle.getBundle("resources/bun
dles/lagarLottery").getString("Ok"),
JOptionPane.INFORMATION_MESSAGE);
}catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resou
rces/bundles/lagarLottery").getString("Error_loading_results"),
java.util.ResourceBundle.getBundle("resou
rces/bundles/lagarLottery").getString("Error"),
JOptionPane.ERROR_MESSAGE);
}
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
dd.dispose();
}
});
});
t.start();
}
else{
dd.dispose();
}
}
};
dd.getOkButton().addActionListener(l);
dd.getCancelButton().addActionListener(l);
dd.setVisible(true);
}catch(IOExceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(
null,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error_loading_results_database"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Fatal_Error"),
JOptionPane.ERROR_MESSAGE);
}
}
privatevoidloadModules(){
this.analysisPanel=newAnalysisControlPanel();
try{
this.analysisPanel.fillAvailableAnalysis();
}
catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Fatal
_error_loading_available_analysis__will_exit_now"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
217
"),JOptionPane.ERROR_MESSAGE);
this.exit();
}
this.generatorPanel=newGeneratorMetaPanel();
try{
this.generatorPanel.loadAvailableGenerators();
}catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Fatal
_error_loading_available_generators__will_exit_now"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
"),JOptionPane.ERROR_MESSAGE);
this.exit();
}
this.printerPanel=newPrinterPanel();
this.filterPanel=newFilterPanel();
try{
this.filterPanel.loadAvailableFilters();
}catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Fatal
_error_loading_available_filters__will_exit_now"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
"),JOptionPane.ERROR_MESSAGE);
this.exit();
}
this.verificatorPanel=newVerificatorPanel();
try{
this.verificatorPanel.loadAvailableVerificators();
}catch(Exceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Fatal
_error_loading_available_verificators__will_exit_now"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
"),JOptionPane.ERROR_MESSAGE);
this.exit();
}
this.mainPanel.add(this.homePanel,"homePanel");
this.mainPanel.add(this.analysisPanel,AnalysisControlPanel.class.getName());
this.mainPanel.add(this.generatorPanel,GeneratorMetaPanel.class.getName());
this.mainPanel.add(this.filterPanel,FilterPanel.class.getName());
this.mainPanel.add(this.printerPanel,PrinterPanel.class.getName());
this.mainPanel.add(this.verificatorPanel,VerificatorPanel.class.getName());
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JToggleButtonanalysisButton;
privatecom.l2fprod.common.swing.JButtonBarbuttonBar;
privatejavax.swing.JMenuItemexitMenuItem;
privatejavax.swing.JToggleButtonfilterButton;
privatejavax.swing.JToggleButtongeneratorButton;
privatejavax.swing.JMenuhelpMenu;
privatejavax.swing.JMenuItemjMenuItem1;
218
privatejavax.swing.JSplitPanejSplitPane;
privatejavax.swing.JMenuItemlistResMenuItem;
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JMenuBarmenuBar;
privatejavax.swing.JMenumenuBarItem;
privatejavax.swing.ButtonGroupmenuGroup;
privatejavax.swing.JScrollPanemenuPane;
privatejavax.swing.JToggleButtonprinterButton;
privatejavax.swing.JPanelstatusPanel;
privatejavax.swing.JMenuItemupdateResMenuItem;
privatejavax.swing.JToggleButtonverificatorButton;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*Main.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.main;
importbr.ufsc.inf.lagar.analysis.CellDataRenderer;
importbr.ufsc.inf.lagar.main.MainFrame;
importcom.jgoodies.looks.plastic.Plastic3DLookAndFeel;
importcom.jgoodies.looks.plastic.PlasticLookAndFeel;
importcom.jgoodies.looks.plastic.PlasticXPLookAndFeel;
importcom.jgoodies.looks.plastic.theme.Silver;
importcom.jgoodies.looks.plastic.theme.SkyBluer;
importjava.awt.Color;
importjava.io.File;
importjava.util.List;
importjavax.swing.UIManager;
publicclassMain{
/**CreatesanewinstanceofMain*/
publicMain(){
}
publicstaticvoidmain(String[]args){
doublemega=1024d*1024d;
System.out.println("TotalMemory="+Runtime.getRuntime().totalMemory()/mega
+"MB");
System.out.println("MaxMemory="+Runtime.getRuntime().maxMemory()/mega+"
219
MB");
System.out.println("Usingjava="+System.getProperty("java.version"));
setLookAndFeel();
FilelocalHome=newFile(LagarLotteryGlobals.LL_HOME);
if(!localHome.exists()){
localHome.mkdir();
}
javax.swing.SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
createAndShowGUI();
}
});
privatestaticvoidcreateAndShowGUI(){
MainFrameframe=newMainFrame();
frame.pack();
frame.setVisible(true);
frame.startApp();
}
privatestaticvoidsetLookAndFeel(){
try{
PlasticLookAndFeel.setTabStyle(PlasticLookAndFeel.TAB_STYLE_METAL_VALUE);
PlasticXPLookAndFeelxp=newPlasticXPLookAndFeel();
xp.setPlasticTheme(newSkyBluer());
UIManager.setLookAndFeel(xp);
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
}
catch(Exceptionex){
try{
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}catch(Exceptionex2){}
}
}
}
/*
*OddEvenAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
220
*/
packagebr.ufsc.inf.lagar.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.DefaultTableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.awt.Color;
importjava.util.ArrayList;
importjava.util.List;
publicclassOddEvenAnalysisextendsDefaultTableChartAnalysis{
/**CreatesanewinstanceofOddEvenAnalysis*/
publicOddEvenAnalysis(){
}
protectedvoidfillTableChart(){
GameCardcardBuffer=newGameCard();
for(intindex=0;this.gci.hasNext();++index){
this.gci.next(cardBuffer);
byte[]balls=cardBuffer.getBalls();
intevens=0;
intodds=0;
for(inti=0;i<balls.length;++i){
intball=balls[i];
if((ball%2)==0)++evens;
else++odds;
}
Stringcategory=evens+""+odds;
this.tcols.get(category)[index]=this.hit;
this.tcols.get(this.columnOne)[index]=new
CellData(String.valueOf(cardBuffer.getSerial()),null,Color.BLACK,false);
Integerdc=this.dataChart.get(category);
this.dataChart.put(category,++dc);
}
publicStringgetName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Even_x_Odd_analysis");
}
publicStringgetHelpInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/analysis/gameanalysis/analysisT
r").getString("Even_x_Odd_analysis_help_info");
}
protectedList<String>buildCategories(){
List<String>result=newArrayList<String>();
221
intnumbersPerCard=getCurrentGameConfiguration().getNumbersPerCard();
//intnumbersPerDraw=getCurrentGameConfiguration().getNumbersPerDrawing();
intnumbersPerDraw=this.gci.getBallsPerCard();
intnumEvens=(numbersPerCard/2);
if(numEvens<numbersPerDraw){
intnumOdds=numbersPerCardnumEvens;
intfirstEven=numbersPerDrawnumOdds;
for(inti=firstEven;i<=numEvens;++i){
Stringcat=i+""+(numbersPerDrawi);
result.add(cat);
}
}else{
for(inti=0;i<=numbersPerDraw;++i){
Stringcat=i+""+(numbersPerDrawi);
result.add(cat);
}
}
returnresult;
}
}
/*
*OddEvenAnalysisTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.core.analysis.gameanalysis;
importbr.ufsc.inf.lagar.analysis.CellDataRenderer;
importbr.ufsc.inf.lagar.analysis.gameanalysis.OddEvenAnalysis;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importjava.io.IOException;
importjava.util.Enumeration;
importjavax.swing.JScrollPane;
importjavax.swing.JTable;
importjavax.swing.ToolTipManager;
importjavax.swing.table.TableColumn;
222
importjunit.framework.*;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.TableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameResultIterator;
importjava.util.ArrayList;
importjava.util.List;
importorg.jfree.chart.JFreeChart;
/**
*
*@authorlagar
*/
publicclassOddEvenAnalysisTestextendsTestCase{
publicvoidtestTable()throwsIOException{
DecisionDialogd=newDecisionDialog(null,true);
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
GameConfigurationgc=availableGames.get(1);
//gc.gameResults.loadResults();
assertNotNull(availableGames);
assertTrue(availableGames.size()!=0);
OddEvenAnalysisinstance=newOddEvenAnalysis();
instance.setBegin(1);
instance.setEnd(20);
instance.setJump(1);
instance.setCurrentGameConfiguration(gc);
instance.calculateAnalysis();
JTabletable=newJTable(instance);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(CellData.class,newCellDataRenderer());
//table.setPreferredScrollableViewportSize(newDimension(20,20));
//table.createDefaultColumnsFromModel();
Enumeration<TableColumn>columns=table.getColumnModel().getColumns();
while(columns.hasMoreElements()){
TableColumnt=columns.nextElement();
t.setMinWidth(50);
t.setPreferredWidth(50);
//t.setResizable(false);
}
JScrollPanepane=newJScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS
_NEEDED);
ToolTipManager.sharedInstance().unregisterComponent(table);
ToolTipManager.sharedInstance().unregisterComponent(table.getTableHeader());
d.getMainPanel().add(pane,"table");
d.pack();
d.setVisible(true);
223
/**
*TestofbuildEvenOddCategoriesmethod,ofclass
br.ufsc.inf.lagar.core.analysis.gameanalysis.OddEvenAnalysis.
*/
publicvoidtestBuildOddEvenCategories(){
System.out.println("buildOddEvenCategories");
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
assertNotNull(availableGames);
assertTrue(availableGames.size()!=0);
OddEvenAnalysisinstance=newOddEvenAnalysis();
instance.setCurrentGameConfiguration(availableGames.get(0));
List<String>expResult=null;
List<String>result=instance.buildEvenOddCategories();
for(Strings:result){
System.out.println(s);
}
}
}
/*
*OddEvenFilter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
importbr.ufsc.inf.lagar.filter.Filterable;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importorg.apache.commons.lang.StringUtils;
publicclassOddEvenFilterextendsAbstractGameFilter{
privateString[]categs;
/**CreatesanewinstanceofOddEvenFilter*/
publicOddEvenFilter(){
}
publicStringgetShortName(){
return
224
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Even_x_Odd");
}
publicStringgetFullName(){
returnthis.getShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Even_x_Odd_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("oddeven_filter_help");
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
String[]params=input.split(Filterable.OR_SEPARATOR);
for(Strings:params){
String[]numbers=s.split("");
if(numbers.length!=2)thrownewTextInputFilterException();
for(Stringn:numbers){
try{
Integer.parseInt(n.trim());
}
catch(NumberFormatExceptionnfex){
thrownewTextInputFilterException(nfex);
}
}
this.categs=newString[params.length];
for(inti=0;i<categs.length;++i){
categs[i]=StringUtils.deleteWhitespace(params[i]);
}
}
publicbooleanfilter(GameCardcard){
Stringcateg=this.getOddEvenCategory(card);
for(Stringp:this.categs){
if(categ.equals(p)){
returnthis.isMode();
}
}
return!(this.isMode());
}
protectedStringgetOddEvenCategory(GameCardcard){
intevens=0;
byte[]balls=card.getBalls();
225
for(byteb:balls){
if(b%2==0){
++evens;
}
}
intodds=balls.lengthevens;
returnevens+""+odds;
}
/*
*PrinterManager.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.printer;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.awt.print.Book;
importjava.awt.print.PageFormat;
importjava.awt.print.PrinterException;
importjava.awt.print.PrinterJob;
importjava.io.File;
importjava.io.IOException;
publicclassPrinterManager{
/**CreatesanewinstanceofPrinterManager*/
publicPrinterManager(){
}
publicvoidprintGameFile(FilellgFile)throwsIOException,PrinterException{
GameCardPrinterprinter=GameManager.getCurrentGame().getGameCardPrinter();
printer.setFile(llgFile);
PrinterJobjob=PrinterJob.getPrinterJob();
job.setPrintable(printer);
booleandoPrint=job.printDialog();
226
if(doPrint){
job.print();
}
}
}
/*
*PrinterPanel.java
*
*Createdon29deMarode2007,20:10
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.printer.PrinterManager;
importjava.awt.print.PrinterException;
importjava.io.File;
importjava.io.IOException;
importjavax.swing.JOptionPane;
/**
*
*@authorlagar
*/
publicclassPrinterPanelextendsjavax.swing.JPanel{
/**CreatesnewformPrinterPanel*/
publicPrinterPanel(){
initComponents();
}
publicvoidprintGames(){
Stringmessage=null;
try{
FilellgFile=newFile(this.fileChooserLLG1.getFilePath());
PrinterManagerm=newPrinterManager();
m.printGameFile(llgFile);
}
catch(IOExceptionioex){
message=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
_loading_file.");
}
catch(PrinterExceptionpex){
message=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery").getString("Error
_printing_file.");
}
if(message!=null){
JOptionPane.showMessageDialog(
this,
message,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
}
/**Thismethodiscalledfromwithintheconstructorto
227
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
jPanel1=newjavax.swing.JPanel();
fileChooserLLG1=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
jPanel2=newjavax.swing.JPanel();
jLabel1=newjavax.swing.JLabel();
jPanel3=newjavax.swing.JPanel();
jLabel2=newjavax.swing.JLabel();
jLabel3=newjavax.swing.JLabel();
printButton=newjavax.swing.JButton();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
simpleInternalFrame1.setTitle(bundle.getString("Print_cards"));//NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getStri
ng("Choose_cards_to_print")));//NOI18N
org.jdesktop.layout.GroupLayoutjPanel1Layout=new
org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,516,
Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
jLabel1.setText(bundle.getString("This_module_will_print_generated_cards_dire
ctly_into_bet_cards_using_your_printer."));//NOI18N
org.jdesktop.layout.GroupLayoutjPanel2Layout=new
org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
228
);
printButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
printButton.setText(bundle.getString("Print"));//NOI18N
printButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
printButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutjPanel3Layout=new
org.jdesktop.layout.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jPanel3Layout.createSequentialGroup()
.add(jLabel2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,209,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(printButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel3,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,210,
Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
jPanel3Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayou
t.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING,jLabel3,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,25,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,printButton,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,jLabel2,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,25,Short.MAX_VALUE))
.addContainerGap())
);
jPanel3Layout.linkSize(newjava.awt.Component[]{jLabel2,jLabel3},
org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(simpleInternalFrame1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
526,Short.MAX_VALUE)
.add(jPanel2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(jPanel3,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
229
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel3,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(145,Short.MAX_VALUE))
);
}//</editorfold>//GENEND:initComponents
privatevoidprintButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_printButtonActionPerformed
this.printGames();
}//GENLAST:event_printButtonActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserLLG1;
privatejavax.swing.JLabeljLabel1;
privatejavax.swing.JLabeljLabel2;
privatejavax.swing.JLabeljLabel3;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JPaneljPanel2;
privatejavax.swing.JPaneljPanel3;
privatejavax.swing.JButtonprintButton;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*PrinterTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.zmisc.test;
230
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.print.PageFormat;
importjava.awt.print.Paper;
importjava.awt.print.Printable;
importjava.awt.print.PrinterException;
importjava.awt.print.PrinterJob;
importjavax.swing.JFrame;
/**
*
*@authorlagar
*/
publicclassPrinterTest{
publicPrinterTest(){
publicvoidtestPrinter(){
PrinterJobjob=PrinterJob.getPrinterJob();
job.setPrintable(newHelloWorldPrinter());
booleandoPrint=job.printDialog();
if(doPrint){
try{
job.print();
}catch(PrinterExceptione){
e.printStackTrace();
}
}
//JFrameabc=newJFrame();
//abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//abc.setVisible(true);
publicstaticvoidmain(String[]args){
newPrinterTest().testPrinter();
}
}
classHelloWorldPrinterimplementsPrintable{
publicintprint(Graphicsg,PageFormatpf,intpageIndex)throws
PrinterException{
if(pageIndex>0){/*Wehaveonlyonepage,and'page'iszerobased*/
returnNO_SUCH_PAGE;
}
/*User(0,0)istypicallyoutsidetheimageablearea,sowemust
*translatebytheXandYvaluesinthePageFormattoavoidclipping
*/
Graphics2Dg2d=(Graphics2D)g;
Paperp=(Paper)pf.getPaper().clone();
p.setImageableArea(0,0,p.getWidth(),p.getHeight());
pf.setPaper(p);
231
doublex=(pf.getWidth()/2)cmToPixel(4.1);
doubley=0;
g2d.translate(x,y);
/*Nowweperformourrendering*/
g2d.fillRect((int)cmToPixel(1.2),(int)cmToPixel(5.82),(int)cmToPixel(0.3),
(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65),(int)cmToPixel(5.82),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65),(int)cmToPixel(5.82),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65+0.65),(int)cmToPixel(5.82),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65+0.65+0.65),(int)cmToPixel(5.82),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2),(int)cmToPixel(5.82+0.325),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65),(int)cmToPixel(5.82+0.325+0.325),
(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65),
(int)cmToPixel(5.82+0.325+0.325+0.325),(int)cmToPixel(0.3),(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65+0.65),
(int)cmToPixel(5.82+0.325+0.325+0.325+0.325),(int)cmToPixel(0.3),
(int)cmToPixel(0.18));
g2d.fillRect((int)cmToPixel(1.2+0.65+0.65+0.65+0.65),
(int)cmToPixel(5.82+0.325+0.325+0.325+0.325+0.325),(int)cmToPixel(0.3),
(int)cmToPixel(0.18));
/*tellthecallerthatthispageispartoftheprinteddocument*/
returnPAGE_EXISTS;
}
privatedoublecmToPixel(doublecm){
doubleinch=this.cmToInch(cm);
returninch*72;
}
privatedoublecmToInch(doublecm){
returncm/2.54;
}
}
/*
*PrinterTestV2.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
232
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.zmisc.test;
importbr.ufsc.inf.lagar.main.GameCardLayout;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.printer.PrinterManager;
importjava.awt.Dimension;
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.Point;
importjava.awt.print.Book;
importjava.awt.print.PageFormat;
importjava.awt.print.Pageable;
importjava.awt.print.Paper;
importjava.awt.print.Printable;
importjava.awt.print.PrinterException;
importjava.awt.print.PrinterJob;
importjava.io.File;
importjava.util.List;
importjavax.print.attribute.HashPrintRequestAttributeSet;
importjavax.print.attribute.PrintRequestAttributeSet;
importjavax.print.attribute.standard.Copies;
importjavax.print.attribute.standard.MediaSize;
importjavax.print.attribute.standard.PageRanges;
importjavax.swing.JFrame;
/**
*
*@authorlagar
*/
publicclassPrinterTestV2{
publicPrinterTestV2(){
publicvoidtestPrinter(){
PrinterJobjob=PrinterJob.getPrinterJob();
CardPrintercardPrinter=newCardPrinter();
job.setPrintable(cardPrinter);
//PrintRequestAttributeSetattr_set=newHashPrintRequestAttributeSet();
//attr_set.add(newPageRanges(1,5));
booleandoPrint=job.printDialog();
233
if(doPrint){
try{
job.print();
}catch(PrinterExceptione){
e.printStackTrace();
}
}
//JFrameabc=newJFrame();
//abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//abc.setVisible(true);
publicstaticvoidmain(String[]args)throwsException{
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
GameConfigurationgc=availableGames.get(0);
gc.getGameResults().loadResults();
GameManager.setCurrentGame(gc);
//newPrinterTestV2().testPrinter();
FilellgFile=newFile("/home/lagar/teste/bb6.llg");
newPrinterManager().printGameFile(llgFile);
//JFrameabc=newJFrame();
//abc.setMinimumSize(newDimension(500,500));
//abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//abc.setVisible(true);
}
}
classCardPrinterimplementsPrintable{
GameConfigurationgc=GameManager.getCurrentGame();
publicintprint(Graphicsg,PageFormatpf,intpageIndex)throws
PrinterException{
if(pageIndex>5){/*Wehaveonlyonepage,and'page'iszerobased*/
returnNO_SUCH_PAGE;
}
/*User(0,0)istypicallyoutsidetheimageablearea,sowemust
*translatebytheXandYvaluesinthePageFormattoavoidclipping
*/
Graphics2Dg2d=(Graphics2D)g;
Paperp=(Paper)pf.getPaper().clone();
p.setImageableArea(0,0,p.getWidth(),p.getHeight());
pf.setPaper(p);
doublex=(pf.getWidth()/2)cmToPixel(4.1);
doubley=0;
g2d.translate(x,y);
GameCardLayoutgcl=gc.getCardLayout();
doublewidth=gcl.getBallWidth();
doubleheight=gcl.getBallHeigth();
int[]nums={1,25,58,74,79};
for(inti:nums){
234
Point.Doublep2d=gcl.getBalls().get(i);
/*Nowweperformourrendering*/
g2d.fillRect((int)cmToPixel(p2d.x),(int)cmToPixel(p2d.y),
(int)cmToPixel(width),(int)cmToPixel(height));
}
List<GameCardLayout.ExtendedBall>exbs=gcl.getExtendedBalls();
Point.Doublep2d=exbs.get(0).getBalls().get(nums.length);
g2d.fillRect((int)cmToPixel(p2d.x),(int)cmToPixel(p2d.y),
(int)cmToPixel(width),(int)cmToPixel(height));
/*tellthecallerthatthispageispartoftheprinteddocument*/
returnPAGE_EXISTS;
}
privatedoublecmToPixel(doublecm){
doubleinch=this.cmToInch(cm);
returninch*72;
}
privatedoublecmToInch(doublecm){
returncm/2.54;
}
}/*
*ProgressDialog.java
*
*Createdon9deMarode2007,20:54
*/
packagebr.ufsc.inf.lagar.ui.dialog;
importbr.ufsc.inf.lagar.ui.ProgressInterface;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.PrintStream;
importjava.text.NumberFormat;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.swing.Timer;
/**
*
*@authorlagar
*/
publicclassProgressDialogextendsjavax.swing.JDialogimplementsActionListener{
privateProgressInterfacepi;
privateTimertimer;
privatebooleanexited=false;
privatelongtime;
SimpleDateFormatsdf=newSimpleDateFormat("mm:ss");
/**CreatesnewformProgressDialog*/
publicProgressDialog(java.awt.Frameparent,booleanmodal,ProgressInterface
pi){
super(parent,modal);
initComponents();
this.timer=newTimer(1000,this);
this.setProgressTarget(pi);
235
}
publicvoidsetProgressTarget(ProgressInterfacepi){
this.pi=pi;
this.jProgressBar1.setValue(0);
this.jProgressBar1.setMinimum(0);
this.jProgressBar1.setMaximum(pi.getMaxProgressValue());
}
publicvoidshowProgressDialog(){
time=System.currentTimeMillis();
this.timer.start();
this.updateProgress();
this.setVisible(true);
}
publicvoidexit(){
if(this.exited)return;
this.exited=true;
this.cancelButton.setEnabled(false);
if(this.timer.isRunning()){
this.timer.stop();
}
this.dispose();
}
privatevoidupdateProgress(){
intvalue=pi.getProgressValue();
Stringtext=pi.getProgressText();
this.jProgressBar1.setValue(value);
this.jProgressBar1.setString(text);
doubledval=value;
doublemax=pi.getMaxProgressValue();
doubleperc=((dval/max)*100.0);
intintperc=(int)perc;
this.setTitle(intperc+"%");
if(value==pi.getMaxProgressValue()&&this.timer.isRunning()){
this.timer.stop();
}
}
publicvoidactionPerformed(ActionEvente){
longnow=System.currentTimeMillis();
longdiff=nowthis.time;
this.updateProgress();
Dated=newDate(diff);
this.timeLabel.setText(sdf.format(d));
}
publicjavax.swing.JLabelgetTitleLabel(){
returntitleLabel;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
236
BEGIN:initComponents
privatevoidinitComponents(){
titleLabel=newjavax.swing.JLabel();
jProgressBar1=newjavax.swing.JProgressBar();
s1=newjavax.swing.JLabel();
s2=newjavax.swing.JLabel();
cancelButton=newjavax.swing.JButton();
timeLabel=newjavax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("");
addWindowListener(newjava.awt.event.WindowAdapter(){
publicvoidwindowClosing(java.awt.event.WindowEventevt){
formWindowClosing(evt);
}
});
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
titleLabel.setText(bundle.getString("Please_wait_generating_your_cards"));//
NOI18N
jProgressBar1.setString("");
jProgressBar1.setStringPainted(true);
cancelButton.setText(bundle.getString("Cancel"));//NOI18N
cancelButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
cancelButtonActionPerformed(evt);
}
});
timeLabel.setFont(newjava.awt.Font("Dialog",0,12));
timeLabel.setForeground(newjava.awt.Color(102,102,102));
timeLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
timeLabel.setText("00:00:00");
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAIL
ING)
.add(timeLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
396,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,jProgressBar1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,396,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,titleLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,396,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,
layout.createSequentialGroup()
.add(s1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,148,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cancelButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(s2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,149,
Short.MAX_VALUE)))
.addContainerGap())
237
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(titleLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jProgressBar1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
37,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(timeLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASEL
INE)
.add(cancelButton)
.add(s1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(s2,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}//</editorfold>//GENEND:initComponents
privatevoidformWindowClosing(java.awt.event.WindowEventevt){//GEN
FIRST:event_formWindowClosing
this.pi.cancel();
this.jProgressBar1.setString(java.util.ResourceBundle.getBundle("resources/bu
ndles/lagarLottery").getString("Cancelled"));
this.exit();
}//GENLAST:event_formWindowClosing
privatevoidcancelButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_cancelButtonActionPerformed
this.pi.cancel();
this.jProgressBar1.setString(java.util.ResourceBundle.getBundle("resources/bu
ndles/lagarLottery").getString("Cancelled"));
this.exit();
}//GENLAST:event_cancelButtonActionPerformed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JButtoncancelButton;
privatejavax.swing.JProgressBarjProgressBar1;
privatejavax.swing.JLabels1;
privatejavax.swing.JLabels2;
privatejavax.swing.JLabeltimeLabel;
privatejavax.swing.JLabeltitleLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*ProgressInterface.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
238
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui;
/**
*
*@authorlagar
*/
publicinterfaceProgressInterface{
publicvoidcancel();
publicStringgetProgressText();
publicintgetProgressValue();
publicintgetMaxProgressValue();
}
/*
*QuinaGameCardPrinter.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.printer;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameCardLayout;
importbr.ufsc.inf.lagar.main.GameManager;
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.Point;
importjava.awt.print.PageFormat;
importjava.awt.print.PrinterException;
importjava.util.List;
publicclassQuinaGameCardPrinterextendsDefaultGameCardPrinter{
239
privateGameCardLayout.ExtendedBallmarkNumber;
/**CreatesanewinstanceofQuinaGameCardPrinter*/
publicQuinaGameCardPrinter(){
@Override
protectedvoidprintExtendedBalls(GameCardgc,Graphicsg,PageFormatpf,int
pageIndex)throwsPrinterException{
if(this.markNumber==null){
GameCardLayoutgcl=GameManager.getCurrentGame().getCardLayout();
List<GameCardLayout.ExtendedBall>exts=gcl.getExtendedBalls();
for(GameCardLayout.ExtendedBallext:exts){
if(ext.getDescription().equals("Numerosporjogo")){
this.markNumber=ext;
break;
}
}
}
Graphics2Dg2d=(Graphics2D)g;
GameCardLayoutgcl=GameManager.getCurrentGame().getCardLayout();
doublewidth=gcl.getBallWidth();
doubleheight=gcl.getBallHeigth();
Point.Doublep2d=this.markNumber.getBalls().get(gc.getBalls().length);
/*Nowweperformourrendering*/
g2d.fillRect((int)cmToPixel(p2d.x),(int)cmToPixel(p2d.y),
(int)cmToPixel(width),(int)cmToPixel(height));
}
/*
*QuinaLoader.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.resultloader;
importbr.ufsc.inf.lagar.main.GameCard;
240
importjava.io.IOException;
importjava.io.InputStream;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
importorg.htmlparser.Node;
importorg.htmlparser.Parser;
importorg.htmlparser.util.NodeList;
importorg.htmlparser.util.ParserException;
importorg.htmlparser.visitors.TagFindingVisitor;
publicclassQuinaLoaderextendsCaixaLoader{
/**CreatesanewinstanceofQuinaLoader*/
publicQuinaLoader(){
//try{
//this.resultPath=new
URL("http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_quina.zip");
//this.resultPath=getClass().getResource("/D_quina.zip");
//}catch(MalformedURLExceptionex){
//ex.printStackTrace();
//}
}
publicList<GameCard>loadResults()throwsIOException{
List<GameCard>quinaResults=newArrayList<GameCard>();
SimpleDateFormatsdf=newSimpleDateFormat("dd/MM/yyyy");
InputStreamin=this.getHtmlStream();
byte[]buf=newbyte[1024];
StringBuildersb=newStringBuilder(300);
intlen=0;
while((len=in.read(buf))>0){
Strings=newString(buf,0,len);
sb.append(s);
}
in.close();
try{
Parserparser=newParser(sb.toString());
sb=null;
String[]tagsToBeFound={"TR"};
TagFindingVisitorvisitor=newTagFindingVisitor(tagsToBeFound);
parser.visitAllNodesWith(visitor);
//Firsttagspecifiedinsearch
Node[]trTags=visitor.getTags(0);
for(inti=1;i<trTags.length;++i){
Noden=trTags[i];
NodeListnl=n.getChildren();
GameCardr=newGameCard(1,null,5);
Nodeserial=nl.elementAt(1);
r.setSerial(Integer.parseInt(serial.getChildren().toHtml()));
241
Nodedate=nl.elementAt(3);
try{
r.setDate(sdf.parse(date.getChildren().toHtml()));
}catch(ParseExceptionex){
thrownewIOException("Errorparsingdateinresultxml");
}
intindex=0;
for(intj=5;j<=13;j+=2){
Nodeball=nl.elementAt(j);
r.setBall((byte)Integer.parseInt(ball.getChildren().toHtml()),
index);
++index;
}
Arrays.sort(r.getBalls());
quinaResults.add(r);
}
}catch(ParserExceptionex){
ex.printStackTrace();
}
returnquinaResults;
}
}
/*
*QuinaLoaderTest.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.persistence.rs;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.resultloader.QuinaLoader;
importbr.ufsc.inf.lagar.resultloader.ResultLoader;
importjava.io.IOException;
importjava.util.List;
importjunit.framework.*;
importjava.net.URL;
/**
*
*@authorlagar
*/
242
publicclassQuinaLoaderTestextendsTestCase{
publicvoidtestQuinaLoader()throwsIOException{
ResultLoaderloader=newQuinaLoader();
List<GameCard>quinaResults=loader.loadResults();
for(GameCardd:quinaResults){
System.out.println(d);
}
}
}
/*
*RadioPanel.java
*
*Createdon12deAbrilde2007,20:32
*/
packagebr.ufsc.inf.lagar.ui.panels;
/**
*
*@authorlagar
*/
publicclassRadioPanelextendsjavax.swing.JPanel{
/**
*CreatesnewformRadioPanel
*/
publicRadioPanel(){
initComponents();
}
publicjavax.swing.JRadioButtongetRadioButton(){
returnradioButton;
}
publicvoidsetRadioButton(javax.swing.JRadioButtonradioButton){
this.radioButton=radioButton;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
radioButton=newjavax.swing.JRadioButton();
setMaximumSize(newjava.awt.Dimension(32767,39));
radioButton.setText("jRadioButton1");
radioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,
0));
radioButton.setMargin(newjava.awt.Insets(0,0,0,0));
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
243
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(radioButton,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,277,
Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(radioButton)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
}//</editorfold>//GENEND:initComponents
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JRadioButtonradioButton;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*ResultLoader.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.resultloader;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.io.IOException;
importjava.net.MalformedURLException;
importjava.util.List;
publicinterfaceResultLoader{
publicList<GameCard>loadResults()throwsIOException;
publicvoidsetResultPath(Stringurl)throwsMalformedURLException;
publicStringgetResultPath();
}
packagebr.ufsc.inf.lagar.utils;
244
/**
*RTSI.java
*
*Created:WedJan2411:15:022001
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*
*/
importjava.io.*;
importjava.net.URL;
importjava.net.JarURLConnection;
importjava.util.ArrayList;
importjava.util.jar.*;
importjava.util.zip.*;
importjava.util.Enumeration;
/**
*Thisutilityclassislookingforalltheclassesimplementingor
*inheritingfromagiveninterfaceorclass.
*(RunTimeSubclassIdentification)
*
*ModifiedbyEuclides(lagar)
*
*
*
*
*
*
*
*
*
*
*
*
*
*@author<ahref="mailto:daniel@satlive.org">DanielLeBerre</a>
*@version1.0
*/
publicclassRTSI{
/**
*Displayalltheclassesinheritingorimplementingagiven
*classinthecurrentlyloadedpackages.
*@paramtosubclassnamethenameoftheclasstoinheritfrom
*/
publicstaticvoidfind(Stringtosubclassname){
try{
245
Classtosubclass=Class.forName(tosubclassname);
Package[]pcks=Package.getPackages();
for(inti=0;i<pcks.length;i++){
find(pcks[i].getName(),tosubclass);
}
}catch(ClassNotFoundExceptionex){
System.err.println("Class"+tosubclassname+"notfound!");
}
}
/**
*Displayalltheclassesinheritingorimplementingagiven
*classinagivenpackage.
*@parampckgnamethefullyqualifiednameofthepackage
*@paramtosubclassthenameoftheclasstoinheritfrom
*@returnlistwiththenames(String)ofclassesfound
*/
publicstaticArrayList<String>find(Stringpckname,Stringtosubclassname){
try{
Classtosubclass=Class.forName(tosubclassname);
returnfind(pckname,tosubclass);
}catch(ClassNotFoundExceptionex){
System.err.println("Class"+tosubclassname+"notfound!");
}
returnnewArrayList<String>();
}
/**
*Displayalltheclassesinheritingorimplementingagiven
*classinagivenpackage.
*@parampckgnamethefullyqualifiednameofthepackage
*@paramtosubclasstheClassobjecttoinheritfrom
*@returnlistwiththenames(String)ofclassesfound
*/
publicstaticArrayList<String>find(Stringpckgname,Classtosubclass){
//Codefromlagar
ArrayList<String>result=newArrayList<String>();
//CodefromJWhich
//======
//Translatethepackagenameintoanabsolutepath
Stringname=newString(pckgname);
if(!name.startsWith("/")){
name="/"+name;
}
name=name.replace('.','/');
//GetaFileobjectforthepackage
URLurl=RTSI.class.getResource(name);
//URLurl=tosubclass.getResource(name);
//URLurl=ClassLoader.getSystemClassLoader().getResource(name);
//SysSystem.out.println(name+">"+url);
//Happensonlyifthejarfileisnotwellconstructed,i.e.
//ifthedirectoriesdonotappearaloneinthejarfilelikehere:
//
//metainf/
//metainf/manifest.mf
//commands/<==IMPORTANT
//commands/Command.class
//commands/DoorClose.class
//commands/DoorLock.class
246
//commands/DoorOpen.class
//commands/LightOff.class
//commands/LightOn.class
//RTSI.class
//
if(url==null)returnresult;
StringurlDir=url.getFile();
urlDir=urlDir.replaceAll("%20","");
Filedirectory=newFile(urlDir);
//Newcode
//======
if(directory.exists()){
//Getthelistofthefilescontainedinthepackage
String[]files=directory.list();
for(inti=0;i<files.length;i++){
//weareonlyinterestedin.classfiles
if(files[i].endsWith(".class")){
//removesthe.classextension
Stringclassname=files[i].substring(0,files[i].length()6);
try{
//Trytocreateaninstanceoftheobject
Objecto=
Class.forName(pckgname+"."+classname).newInstance();
if(tosubclass.isInstance(o)){
//System.out.println(classname);
result.add(classname);
}
}catch(ClassNotFoundExceptioncnfex){
System.err.println(cnfex);
}catch(InstantiationExceptioniex){
//Wetrytoinstanciateaninterface
//oranobjectthatdoesnothavea
//defaultconstructor
}catch(IllegalAccessExceptioniaex){
//Theclassisnotpublic
}
}
}
}else{
try{
//Itdoesnotworkwiththefilesystem:wemust
//beinthecaseofapackagecontainedinajarfile.
JarURLConnectionconn=(JarURLConnection)url.openConnection();
Stringstarts=conn.getEntryName();
JarFilejfile=conn.getJarFile();
Enumeratione=jfile.entries();
while(e.hasMoreElements()){
ZipEntryentry=(ZipEntry)e.nextElement();
Stringentryname=entry.getName();
if(entryname.startsWith(starts)
&&(entryname.lastIndexOf('/')<=starts.length())
&&entryname.endsWith(".class")){
Stringclassname=entryname.substring(0,entryname.length()
6);
if(classname.startsWith("/"))
classname=classname.substring(1);
classname=classname.replace('/','.');
try{
//Trytocreateaninstanceoftheobject
Objecto=Class.forName(classname).newInstance();
247
if(tosubclass.isInstance(o)){
//System.out.println(classname.substring(classname.la
stIndexOf('.')+1));
result.add(classname.substring(classname.lastIndexOf(
'.')+1));
}
}catch(ClassNotFoundExceptioncnfex){
System.err.println(cnfex);
}catch(InstantiationExceptioniex){
//Wetrytoinstanciateaninterface
//oranobjectthatdoesnothavea
//defaultconstructor
}catch(IllegalAccessExceptioniaex){
//Theclassisnotpublic
}
}
}
}catch(IOExceptionioex){
System.err.println(ioex);
}
}
returnresult;
}
/**
*Displayallthefilesinapackage.
*@parampckgnamethefullyqualifiednameofthepackage
*@paramfileFilterthefilesuffixex:xmlnullifwantallfiles
*@returnlistwiththenames(String)offilesfound
*/
publicstaticArrayList<String>findFiles(Stringpckgname,StringfileFilter){
//Codefromlagar
ArrayList<String>result=newArrayList<String>();
//CodefromJWhich
//======
//Translatethepackagenameintoanabsolutepath
Stringname=newString(pckgname);
if(!name.startsWith("/")){
name="/"+name;
}
name=name.replace('.','/');
//GetaFileobjectforthepackage
URLurl=RTSI.class.getResource(name);
//URLurl=tosubclass.getResource(name);
//URLurl=ClassLoader.getSystemClassLoader().getResource(name);
//SysSystem.out.println(name+">"+url);
//Happensonlyifthejarfileisnotwellconstructed,i.e.
//ifthedirectoriesdonotappearaloneinthejarfilelikehere:
//
//metainf/
//metainf/manifest.mf
//commands/<==IMPORTANT
//commands/Command.class
//commands/DoorClose.class
//commands/DoorLock.class
//commands/DoorOpen.class
//commands/LightOff.class
//commands/LightOn.class
//RTSI.class
248
//
if(url==null)returnresult;
StringurlDir=url.getFile();
urlDir=urlDir.replaceAll("%20","");
Filedirectory=newFile(urlDir);
//Newcode
//======
if(directory.exists()){
//Getthelistofthefilescontainedinthepackage
String[]files=directory.list();
for(inti=0;i<files.length;i++){
if(fileFilter!=null){
if(files[i].toLowerCase().endsWith(fileFilter.toLowerCase())){
result.add(files[i]);
}
}
else{
result.add(files[i]);
}
}
}else{
try{
//Itdoesnotworkwiththefilesystem:wemust
//beinthecaseofapackagecontainedinajarfile.
JarURLConnectionconn=(JarURLConnection)url.openConnection();
Stringstarts=conn.getEntryName();
JarFilejfile=conn.getJarFile();
Enumeratione=jfile.entries();
while(e.hasMoreElements()){
ZipEntryentry=(ZipEntry)e.nextElement();
Stringentryname=entry.getName();
if(entryname.startsWith(starts)
&&(entryname.lastIndexOf('/')<=starts.length())){
if(fileFilter!=null){
if
(entryname.toLowerCase().endsWith(fileFilter.toLowerCase())){
result.add(entryname);
}
}
else{
result.add(entryname);
}
}
}
}catch(IOExceptionioex){
System.err.println(ioex);
}
}
returnresult;
}
}//RTSI
/*
*SerialCardFilter.java
249
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter.gamefilter;
importbr.ufsc.inf.lagar.filter.AbstractGameFilter;
importbr.ufsc.inf.lagar.filter.TextInputFilterException;
importbr.ufsc.inf.lagar.main.GameCard;
importorg.apache.commons.lang.StringUtils;
publicclassSerialCardFilterextendsAbstractGameFilter{
privateintjump;
/**CreatesanewinstanceofSerialCardFilter*/
publicSerialCardFilter(){
}
publicvoidvalidateInput(Stringinput)throwsTextInputFilterException{
try{
String[]arr=input.split("=");
for(inti=0;i<arr.length;++i){
arr[i]=StringUtils.deleteWhitespace(arr[i]);
}
this.jump=Integer.parseInt(arr[1]);
}
catch(Exceptionex){
thrownewTextInputFilterException(ex);
}
publicStringgetShortName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Serial_filter");
}
publicStringgetFullName(){
returnthis.getShortName();
}
publicStringgetDescription(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
250
etString("Serial_filter_description");
}
publicStringgetFilterHelp(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/filter/gamefilter/filtersTr").g
etString("Serial_filter_help");
}
publicbooleanfilter(GameCardcard){
intserial=card.getSerial();
if(serial<this.jump)return!(this.isMode());
if(serial%this.jump==0)returnthis.isMode();
return!(this.isMode());
}
}
/*
*SimpleVerificator.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.verify.verificators;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importbr.ufsc.inf.lagar.verify.VerificatorInterface;
importjava.io.File;
importjava.io.IOException;
importjava.text.NumberFormat;
importjava.util.Arrays;
importjavax.swing.JEditorPane;
importjavax.swing.JScrollPane;
importjavax.swing.SwingUtilities;
publicclassSimpleVerificatorimplementsVerificatorInterface{
privateGameCardresult;
privateFilecardsFile;
privateNumberFormatnf;
251
privateNumberFormatnfb;
/**CreatesanewinstanceofSimpleVerificator*/
publicSimpleVerificator(){
nf=NumberFormat.getIntegerInstance();
nf.setMinimumIntegerDigits(4);
nfb=NumberFormat.getIntegerInstance();
nfb.setMinimumIntegerDigits(2);
}
publicvoidsetCards(FilellgFile)throwsIOException{
this.cardsFile=llgFile;
}
publicStringgetVName(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/verificators/verificator
sTr").getString("Simple_verificator");
}
publicStringgetMoreInfo(){
return
java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/verificators/verificator
sTr").getString("todo_simple_verificator_more_info");
}
publicvoidrunVerificator(){
finalDecisionDialogdd=newDecisionDialog(null,false);
dd.getTitlePanel().setTitle(this.getVName());
dd.getButtonsPanel().setVisible(false);
JEditorPaneeditor=newJEditorPane("text/html","");
JScrollPanescroll=newJScrollPane(
editor,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dd.getMainPanel().add(scroll,scroll.getClass().getName());
editor.setText(this.computeResult());
scroll.revalidate();
dd.repaint();
SwingUtilities.invokeLater(newRunnable(){
publicvoidrun(){
dd.setVisible(true);
}
});
}
privateStringcomputeResult(){
GameConfigurationgc=GameManager.getCurrentGame();
StringBuildersb=newStringBuilder();
sb.append("<html>");
GenCardIOio=null;
try{
io=newGenCardIO(this.cardsFile);
int[]cats=newint[gc.getNumbersPerDrawing()+1];
252
while(io.hasNext()){
GameCardgameCard=io.next();
inthits=this.computeHits(gameCard);
++cats[hits];
this.writeGame(sb,gameCard,hits);
this.writeSummary(sb,cats);
}
catch(IOExceptionioex){
ioex.printStackTrace();
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/ve
rificators/verificatorsTr").getString("Error_computing_results"));
returnsb.toString();
}
finally{
sb.append("</html>");
if(io!=null)io.close();
}
returnsb.toString();
}
privateintcomputeHits(GameCardcurrGame){
byte[]r=this.result.getBalls();
byte[]g=currGame.getBalls();
inthits=0;
for(inti=0;i<g.length;++i){
if(Arrays.binarySearch(r,g[i])>=0){
++hits;
}
}
returnhits;
}
privatevoidwriteGame(StringBuildersb,GameCardgc,inthits){
sb.append("<b>");
sb.append(nf.format(gc.getSerial()));
sb.append("</b>");
sb.append(":");
sb.append(nfb.format(hits));
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/verifi
cators/verificatorsTr").getString("_hits"));
sb.append("<br><br>");
}
privatevoidwriteSummary(StringBuildersb,int[]hits){
sb.append("<b>");
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/verifi
cators/verificatorsTr").getString("===========_Summary_==========="));
sb.append("</b>");
sb.append("<br>");
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/verifi
cators/verificatorsTr").getString("Hits_x_number_of_cards"));
sb.append("<br><br>");
253
for(inti=0;i<hits.length;++i){
sb.append(nfb.format(i));
sb.append("");
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/ve
rificators/verificatorsTr").getString("hits"));
sb.append("=");
sb.append(nfb.format(hits[i]));
sb.append("");
sb.append(java.util.ResourceBundle.getBundle("br/ufsc/inf/lagar/verify/ve
rificators/verificatorsTr").getString("cards."));
sb.append("<br>");
}
}
publicvoidsetResult(GameCardgc){
this.result=gc;
}
}
/*
*SingleFilterPanel.java
*
*Createdon29deMarode2007,21:36
*/
packagebr.ufsc.inf.lagar.ui.panels.filter;
importbr.ufsc.inf.lagar.filter.Filterable;
importjava.awt.Color;
importjava.awt.Component;
importjava.awt.event.MouseListener;
importjavax.swing.border.LineBorder;
/**
*
*@authorlagar
*/
publicclassSingleFilterPanelextendsjavax.swing.JPanel{
privateFilterablefilter;
privateFilterSelectPanelparentFp;
privateintposition;
privateStringACCEPT="Accept";
privateStringREJECT="Reject";
/**CreatesnewformSingleFilterPanel*/
publicSingleFilterPanel(Filterablef,intposition,FilterSelectPanelparentFp)
{
initComponents();
this.parentFp=parentFp;
this.filter=f;
this.setPosition(position);
this.numberLabel.setText(String.valueOf(position)+"");
this.filterLabel.setText(f.getShortName());
this.acRjCombo.addItem(ACCEPT);
this.acRjCombo.addItem(REJECT);
this.acRjCombo.setSelectedItem(REJECT);
//mouselistener
MouseListenerml=this.getMouseListeners()[0];
Component[]cs=this.acRjCombo.getComponents();
254
for(inti=0;i<cs.length;i++){
cs[i].addMouseListener(ml);
}
this.getFilterField().addMouseListener(ml);
}
publicFilterablegetFilter(){
returnfilter;
}
publicintgetPosition(){
returnposition;
}
publicvoidsetPosition(intposition){
this.position=position;
this.numberLabel.setText(position+"");
}
publicjavax.swing.JTextFieldgetFilterField(){
returnfilterField;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
filterLabel=newjavax.swing.JLabel();
filterField=newjavax.swing.JTextField();
acRjCombo=newjavax.swing.JComboBox();
numberLabel=newjavax.swing.JLabel();
setMaximumSize(newjava.awt.Dimension(32767,50));
setMinimumSize(newjava.awt.Dimension(200,50));
addMouseListener(newjava.awt.event.MouseAdapter(){
publicvoidmousePressed(java.awt.event.MouseEventevt){
formMousePressed(evt);
}
});
filterLabel.setText("Filtername");
acRjCombo.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
acRjComboActionPerformed(evt);
}
});
numberLabel.setText("1");
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.add(numberLabel)
255
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filterLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,70,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(acRjCombo,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(filterField,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,223,
Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASEL
INE)
.add(numberLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
24,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(filterLabel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
26,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(acRjCombo,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
24,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(filterField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
26,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
}//</editorfold>//GENEND:initComponents
privatevoidacRjComboActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_acRjComboActionPerformed
StringselectedItem=this.acRjCombo.getSelectedItem().toString();
this.filter.setAcceptReject(selectedItem.equals(ACCEPT));
}//GENLAST:event_acRjComboActionPerformed
privatevoidformMousePressed(java.awt.event.MouseEventevt){//GEN
FIRST:event_formMousePressed
this.parentFp.setSelectedFilter(this);
}//GENLAST:event_formMousePressed
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JComboBoxacRjCombo;
privatejavax.swing.JTextFieldfilterField;
privatejavax.swing.JLabelfilterLabel;
privatejavax.swing.JLabelnumberLabel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*TableAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
256
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importjava.awt.CardLayout;
importjava.awt.FlowLayout;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Enumeration;
importjava.util.List;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JTable;
importjavax.swing.ToolTipManager;
importjavax.swing.event.TableModelListener;
importjavax.swing.table.TableColumn;
importjavax.swing.table.TableModel;
importorg.jfree.chart.JFreeChart;
publicabstractclassTableAnalysisextendsAnalysisimplementsTableModel{
/**
*CreatesanewinstanceofTableAnalysis
*/
publicTableAnalysis(){
}
publicabstractintgetRowCount();
publicabstractintgetColumnCount();
publicabstractStringgetColumnName(intcolumnIndex);
publicabstractCellDatagetCellDataAt(introwIndex,intcolumnIndex);
publicList<JPanel>getPanels(){
JPanelpanel=newJPanel();
panel.setLayout(newCardLayout());
panel.setName("Table");
JScrollPanescroll=newJScrollPane(getTable(),
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scroll,"scroll");
List<JPanel>panels=newArrayList<JPanel>();
panels.add(panel);
returnpanels;
}
protectedJTablegetTable(){
JTabletable=newJTable(this);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
257
table.setDefaultRenderer(CellData.class,newCellDataRenderer());
Enumeration<TableColumn>columns=table.getColumnModel().getColumns();
while(columns.hasMoreElements()){
TableColumnt=columns.nextElement();
t.setMinWidth(20);
t.setPreferredWidth(43);
//t.setResizable(false);
}
returntable;
}
publicClass<?>getColumnClass(intcolumnIndex){
returnCellData.class;
}
publicbooleanisCellEditable(introwIndex,intcolumnIndex){
returnfalse;
}
publicObjectgetValueAt(introwIndex,intcolumnIndex){
returnthis.getCellDataAt(rowIndex,columnIndex);
}
publicvoidsetValueAt(ObjectaValue,introwIndex,intcolumnIndex){
}
publicvoidaddTableModelListener(TableModelListenerl){
}
publicvoidremoveTableModelListener(TableModelListenerl){
}
}
/*
*TableChartAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.analysis;
importjava.util.List;
importjavax.swing.JPanel;
importorg.jfree.chart.ChartPanel;
importorg.jfree.chart.JFreeChart;
258
publicabstractclassTableChartAnalysisextendsTableAnalysisimplementsChartable
{
publicList<JPanel>getPanels(){
List<JPanel>panels=super.getPanels();
JFreeChartchart=getChart();
if(chart!=null){
ChartPanelpanel=newChartPanel(getChart());
panel.setName("Chart");
panels.add(panel);
}
returnpanels;
}
}
/*
*TermsDialog.java
*
*Createdon16deMaiode2007,22:30
*/
packagebr.ufsc.inf.lagar.main;
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
/**
*
*@authorlagar
*/
publicclassTermsDialogextendsjavax.swing.JDialog{
/**CreatesnewformTermsDialog*/
publicTermsDialog(java.awt.Frameparent,booleanmodal){
super(parent,modal);
initComponents();
this.setLocationRelativeTo(null);
try{
InputStreamis=getClass().getResourceAsStream("/resources/LICENSE");
BufferedReaderr=newBufferedReader(newInputStreamReader(is));
StringBuildersb=newStringBuilder();
Stringline=null;
while((line=r.readLine())!=null){
sb.append(line);
sb.append("\n");
}
this.jTextArea1.setText(sb.toString());
}
catch(Exceptionex){
this.jTextArea1.setText("SeefileLICENSE");
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
259
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
jScrollPane1=newjavax.swing.JScrollPane();
jTextArea1=newjavax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Terms");
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,600,
Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,400,
Short.MAX_VALUE)
);
pack();
}//</editorfold>//GENEND:initComponents
/**
*@paramargsthecommandlinearguments
*/
publicstaticvoidmain(Stringargs[]){
java.awt.EventQueue.invokeLater(newRunnable(){
publicvoidrun(){
newTermsDialog(newjavax.swing.JFrame(),true).setVisible(true);
}
});
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JScrollPanejScrollPane1;
privatejavax.swing.JTextAreajTextArea1;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*TesteMain.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
260
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.verify.animated1.osc;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.InputStream;
publicclassTesteMain{
/**CreatesanewinstanceofTesteMain*/
publicTesteMain(){
}
publicstaticvoidmain(String[]args)throwsException{
InputStreamis=
TesteMain.class.getResourceAsStream("/resources/snd/pop.au");
ByteArrayOutputStreambos=newByteArrayOutputStream();
byte[]buf=newbyte[8192];
intn=0;
while((n=is.read(buf))!=1){
bos.write(buf,0,n);
}
byte[]arrFinal=bos.toByteArray();
ByteArrayInputStreamohh=newByteArrayInputStream(arrFinal);
inti=0;
while(i<5){
AudioPlayer.main(ohh);
++i;
//is=TesteMain.class.getResourceAsStream("/resources/snd/pop.au");
ohh=newByteArrayInputStream(arrFinal);
}
}
/*
*TestOddEvenAnalysis.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
261
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.zmisc.test;
importbr.ufsc.inf.lagar.analysis.CellDataRenderer;
importbr.ufsc.inf.lagar.analysis.gameanalysis.OddEvenAnalysis;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.ui.dialog.DecisionDialog;
importjava.io.IOException;
importjava.util.Enumeration;
importjavax.swing.JScrollPane;
importjavax.swing.JTable;
importjavax.swing.ToolTipManager;
importjavax.swing.table.TableColumn;
importbr.ufsc.inf.lagar.analysis.CellData;
importbr.ufsc.inf.lagar.analysis.TableChartAnalysis;
importbr.ufsc.inf.lagar.main.GameResultIterator;
importjava.util.ArrayList;
importjava.util.List;
importorg.jfree.chart.JFreeChart;
publicclassTestOddEvenAnalysis{
/**CreatesanewinstanceofTestOddEvenAnalysis*/
publicTestOddEvenAnalysis(){
}
publicstaticvoidtestTable()throwsIOException{
DecisionDialogd=newDecisionDialog(null,true);
List<GameConfiguration>availableGames=GameManager.getAvailableGames();
GameConfigurationgc=availableGames.get(0);
gc.getGameResults().loadResults();
OddEvenAnalysisinstance=newOddEvenAnalysis();
instance.setBegin(1);
instance.setEnd(179);
instance.setJump(1);
instance.setCurrentGameConfiguration(gc);
instance.calculateAnalysis();
JTabletable=newJTable(instance);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(CellData.class,newCellDataRenderer());
//table.setPreferredScrollableViewportSize(newDimension(20,20));
//table.createDefaultColumnsFromModel();
Enumeration<TableColumn>columns=table.getColumnModel().getColumns();
while(columns.hasMoreElements()){
TableColumnt=columns.nextElement();
t.setMinWidth(50);
t.setPreferredWidth(50);
//t.setResizable(false);
}
JScrollPanepane=newJScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
262
JScrollPane.HORIZONTAL_SCROLLBAR_AS
_NEEDED);
ToolTipManager.sharedInstance().unregisterComponent(table);
ToolTipManager.sharedInstance().unregisterComponent(table.getTableHeader());
d.getMainPanel().add(pane,"table");
d.pack();
d.setResizable(true);
d.setVisible(true);
publicstaticvoidmain(String[]args)throwsIOException{
testTable();
}
}
/*
*TextInputFilterException.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.filter;
publicclassTextInputFilterExceptionextendsException{
/**CreatesanewinstanceofTextInputFilterException*/
publicTextInputFilterException(){
}
publicTextInputFilterException(Stringmessage){
super(message);
}
publicTextInputFilterException(Stringmessage,Throwablet){
super(message,t);
}
publicTextInputFilterException(Throwablet){
super(t);
}
}
/*
*UpdateDbPanel.java
263
*
*Createdon8deAbrilde2007,16:58
*/
packagebr.ufsc.inf.lagar.ui.panels;
/**
*
*@authorlagar
*/
publicclassUpdateDbPanelextendsjavax.swing.JPanel{
/**CreatesnewformUpdateDbPanel*/
publicUpdateDbPanel(){
initComponents();
}
publicjavax.swing.JLabelgetInfoLabel(){
returninfoLabel;
}
publicjavax.swing.JTextFieldgetUrlField(){
returnurlField;
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
infoLabel=newjavax.swing.JLabel();
fromUrlPanel=newjavax.swing.JPanel();
urlField=newjavax.swing.JTextField();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
fromUrlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.ge
tString("update_from_url")));//NOI18N
org.jdesktop.layout.GroupLayoutfromUrlPanelLayout=new
org.jdesktop.layout.GroupLayout(fromUrlPanel);
fromUrlPanel.setLayout(fromUrlPanelLayout);
fromUrlPanelLayout.setHorizontalGroup(
fromUrlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(urlField,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,498,
Short.MAX_VALUE)
);
fromUrlPanelLayout.setVerticalGroup(
fromUrlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(urlField,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,31,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
264
layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAIL
ING)
.add(org.jdesktop.layout.GroupLayout.LEADING,fromUrlPanel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING,infoLabel,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,508,Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(infoLabel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,83,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(fromUrlPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}//</editorfold>//GENEND:initComponents
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JPanelfromUrlPanel;
privatejavax.swing.JLabelinfoLabel;
privatejavax.swing.JTextFieldurlField;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*VerificatorInterface.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.verify;
importbr.ufsc.inf.lagar.main.GameCard;
importjava.io.File;
importjava.io.IOException;
/**
*
*@authorlagar
265
*/
publicinterfaceVerificatorInterface{
publicvoidsetCards(FilellgFile)throwsIOException;
publicvoidsetResult(GameCardgc);
publicStringgetVName();
publicStringgetMoreInfo();
publicvoidrunVerificator();
}
/*
*VerificatorPanel.java
*
*Createdon12deAbrilde2007,20:23
*/
packagebr.ufsc.inf.lagar.ui.panels;
importbr.ufsc.inf.lagar.generator.GenCardIO;
importbr.ufsc.inf.lagar.main.GameCard;
importbr.ufsc.inf.lagar.main.GameConfiguration;
importbr.ufsc.inf.lagar.main.GameManager;
importbr.ufsc.inf.lagar.utils.RTSI;
importbr.ufsc.inf.lagar.verify.VerificatorInterface;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjavax.swing.JOptionPane;
importjavax.swing.JRadioButton;
importorg.apache.commons.lang.StringUtils;
/**
*
*@authorlagar
*/
publicclassVerificatorPanelextendsjavax.swing.JPanelimplementsActionListener{
privateHashMap<String,VerificatorInterface>vs=newHashMap<String,
VerificatorInterface>();
privateStringselection;
privateGameCardresult;
/**CreatesnewformVerificatorPanel*/
publicVerificatorPanel(){
initComponents();
this.fileChooserLLG1.setMode(FileChooserLLG.ChooserMode.LOAD_MODE);
}
publicvoidloadAvailableVerificators()throwsException{
GameConfigurationcurrent=GameManager.getCurrentGame();
StringpackageName="br.ufsc.inf.lagar.verify.verificators";
booleanfirst=true;
266
ArrayList<String>classes=RTSI.find(packageName,
VerificatorInterface.class);
for(Stringclazz:classes){
clazz=packageName+"."+clazz;
VerificatorInterfaceverificator=(VerificatorInterface)
Class.forName(clazz).newInstance();
this.vs.put(verificator.getVName(),verificator);
RadioPanelrp=newRadioPanel();
rp.getRadioButton().setText(verificator.getVName());
rp.getRadioButton().setActionCommand(verificator.getVName());
rp.getRadioButton().addActionListener(this);
this.buttonGroup1.add(rp.getRadioButton());
this.versPanel.add(rp);
if(first){
rp.getRadioButton().setSelected(true);
first=false;
this.selection=verificator.getVName();
}
this.jScrollPane1.revalidate();
this.repaint();
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
buttonGroup1=newjavax.swing.ButtonGroup();
simpleInternalFrame1=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
jScrollPane1=newjavax.swing.JScrollPane();
versPanel=newjavax.swing.JPanel();
labelSepRight=newjavax.swing.JLabel();
labelSepLeft=newjavax.swing.JLabel();
infoButton=newjavax.swing.JButton();
runButton=newjavax.swing.JButton();
fileChooserLLG1=newbr.ufsc.inf.lagar.ui.panels.FileChooserLLG();
jPanel1=newjavax.swing.JPanel();
jScrollPane2=newjavax.swing.JScrollPane();
resultArea=newjavax.swing.JTextArea();
java.util.ResourceBundlebundle=
java.util.ResourceBundle.getBundle("resources/bundles/lagarLottery");//NOI18N
simpleInternalFrame1.setTitle(bundle.getString("Verificators"));//NOI18N
jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.ge
tString("Verificators_impls")));//NOI18N
versPanel.setLayout(newjavax.swing.BoxLayout(versPanel,
javax.swing.BoxLayout.Y_AXIS));
267
jScrollPane1.setViewportView(versPanel);
infoButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/info.png")));
infoButton.setText(bundle.getString("Info"));//NOI18N
infoButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
infoButtonActionPerformed(evt);
}
});
runButton.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/resources/16x16/runprog.png")));
runButton.setText(bundle.getString("Run"));//NOI18N
runButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
runButtonActionPerformed(evt);
}
});
fileChooserLLG1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle
.getString("Game_to_verify")));//NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getStri
ng("Result")));//NOI18N
jPanel1.setMinimumSize(newjava.awt.Dimension(100,60));
jPanel1.setPreferredSize(newjava.awt.Dimension(100,60));
resultArea.setColumns(20);
resultArea.setLineWrap(true);
resultArea.setRows(3);
resultArea.setWrapStyleWord(true);
jScrollPane2.setViewportView(resultArea);
org.jdesktop.layout.GroupLayoutjPanel1Layout=new
org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jScrollPane2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,535,
Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING
)
.add(jScrollPane2,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,54,
Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(labelSepLeft,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,178,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(runButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(infoButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(labelSepRight,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
179,Short.MAX_VALUE))
268
.add(simpleInternalFrame1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
545,Short.MAX_VALUE)
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,545,
Short.MAX_VALUE)
.add(jPanel1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,545,
Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING,jScrollPane1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,545,Short.MAX_VALUE)
);
layout.linkSize(newjava.awt.Component[]{infoButton,runButton},
org.jdesktop.layout.GroupLayout.HORIZONTAL);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(simpleInternalFrame1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(fileChooserLLG1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,78,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,193,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAIL
ING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.B
ASELINE)
.add(infoButton)
.add(runButton))
.add(labelSepRight,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(labelSepLeft,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,25,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.linkSize(newjava.awt.Component[]{labelSepLeft,labelSepRight},
org.jdesktop.layout.GroupLayout.VERTICAL);
layout.linkSize(newjava.awt.Component[]{infoButton,runButton},
org.jdesktop.layout.GroupLayout.VERTICAL);
}//</editorfold>//GENEND:initComponents
privatevoidrunButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_runButtonActionPerformed
if(this.validateInput()){
this.processRunButton();
}
}//GENLAST:event_runButtonActionPerformed
privatevoidinfoButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_infoButtonActionPerformed
269
this.processInfoButton();
}//GENLAST:event_infoButtonActionPerformed
privatevoidprocessRunButton(){
finalVerificatorInterfacevi=this.vs.get(this.selection);
vi.setResult(this.result);
try{
vi.setCards(newFile(this.fileChooserLLG1.getFilePath()));
}catch(IOExceptionex){
ex.printStackTrace();
}
Threadt=newThread(newRunnable(){
publicvoidrun(){
vi.runVerificator();
}
});
t.start();
}
privatevoidprocessInfoButton(){
thrownewUnsupportedOperationException("Notyetimplemented");
}
publicvoidactionPerformed(ActionEvente){
this.selection=e.getActionCommand();
}
privatebooleanvalidateInput(){
GameConfigurationgc=GameManager.getCurrentGame();
StringfilePath=this.fileChooserLLG1.getFilePath();
GenCardIOio=null;
try{
io=newGenCardIO(newFile(filePath));
Stringresult=this.resultArea.getText();
String[]rn=result.trim().split("");
byte[]arr=newbyte[rn.length];
for(inti=0;i<rn.length;++i){
Strings=StringUtils.deleteWhitespace(rn[i]);
arr[i]=Byte.parseByte(s);
}
Arrays.sort(arr);
if(gc.getNumbersPerDrawing()!=arr.length){
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Invalid_result._You_must_type_the_correct_amount_of_numbers."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
if(arr[arr.length1]>gc.getNumbersPerCard()){
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
270
y").getString("Invalid_result._You_typed_one_ball_that_is_impossible_to_occur."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
this.result=newGameCard(0,null,arr.length);
this.result.setBalls(arr);
}catch(IOExceptionex){
ex.printStackTrace();
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Invalid_file"),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
catch(NumberFormatExceptionnfex){
nfex.printStackTrace();
JOptionPane.showMessageDialog(
this,
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Invalid_result._Use_character_''_as_a_separator."),
java.util.ResourceBundle.getBundle("resources/bundles/lagarLotter
y").getString("Error"),
JOptionPane.ERROR_MESSAGE);
returnfalse;
}
finally{
if(io!=null)io.close();
}
returntrue;
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.ButtonGroupbuttonGroup1;
privatebr.ufsc.inf.lagar.ui.panels.FileChooserLLGfileChooserLLG1;
privatejavax.swing.JButtoninfoButton;
privatejavax.swing.JPaneljPanel1;
privatejavax.swing.JScrollPanejScrollPane1;
privatejavax.swing.JScrollPanejScrollPane2;
privatejavax.swing.JLabellabelSepLeft;
privatejavax.swing.JLabellabelSepRight;
privatejavax.swing.JTextArearesultArea;
privatejavax.swing.JButtonrunButton;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFramesimpleInternalFrame1;
privatejavax.swing.JPanelversPanel;
//Endofvariablesdeclaration//GENEND:variables
}
/*
*WizardPanel.java
*
*Copyright(C)2006EuclidesPinheirodeMelo<lagar_lottery@yahoo.com.br>
*
*Thisprogramisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULibraryGeneralPublic
271
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2oftheLicense,or(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNU
*LibraryGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNULibraryGeneralPublic
*Licensealongwiththisprogram;ifnot,writetothe
*FreeSoftwareFoundation,Inc.,59TemplePlaceSuite330,
*Boston,MA021111307,USA.
*
*/
packagebr.ufsc.inf.lagar.ui.wizard;
importjava.awt.CardLayout;
importjava.awt.Component;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Stack;
publicclassWizardPanelextendsjavax.swing.JPanel{
privatefinalStringNEXT="Next>";
privatefinalStringFINISH="Finish";
privateStack<String>pagePath=newStack<String>();
privateMap<String,IWizardPage>pageMap=newHashMap<String,IWizardPage>();
privateList<String>pages=newArrayList<String>();
/**CreatesnewformWizardPkcs11Panel*/
publicWizardPanel(){
initComponents();
posInit();
}
privatevoidposInit(){
this.getBackButton().setEnabled(false);
this.getNextButton().setText(NEXT);
}
publicvoidaddPage(IWizardPagepanel){
StringpageName=panel.getPageName();
if(pageName==null||pageName.equals("")){
thrownewIllegalArgumentException("Pagenamecannotbeemptyornull");
}
if(this.pageMap.containsKey(pageName)){
thrownewIllegalArgumentException("Alreadyhaveonepagewithname:
"+pageName);
}
this.pageMap.put(pageName,panel);
this.pages.add(pageName);
if(this.pagePath.isEmpty()){
272
this.pagePath.push(pageName);
}
panel.setWizardPanel(this);
this.mainPanel.add((Component)panel,pageName);
}
protectedvoidshowPage(StringpageName){
if(this.pagePath.size()<=1)this.getBackButton().setEnabled(false);
elsethis.getBackButton().setEnabled(true);
CardLayoutcards=(CardLayout)this.mainPanel.getLayout();
cards.show(this.mainPanel,pageName);
}
protectedvoidgoNextPage(){
this.deactivateActualPage();
Stringcurrent=this.pagePath.peek();
IWizardPagepanel=this.pageMap.get(current);
StringnextPage=panel.getNextPageName();
if(nextPage==null){
nextPage=this.getNextPage(current);
}
this.pagePath.push(nextPage);
IWizardPagecurrentPanel=this.pageMap.get(nextPage);
currentPanel.activatePage();
if(this.isLastPage(nextPage)){
this.nextButton.setText(FINISH);
}
this.showPage(nextPage);
}
protectedvoidgoPreviousPage(){
this.nextButton.setText(NEXT);
this.deactivateActualPage();
this.pagePath.pop();
Stringpage=this.pagePath.peek();
IWizardPagepanelAtual=this.pageMap.get(page);
panelAtual.activatePage();
this.showPage(page);
}
protectedvoiddeactivateActualPage(){
if(!this.pagePath.isEmpty()){
IWizardPagepanel=this.pageMap.get(this.pagePath.peek());
panel.deactivatePage();
}
}
protectedbooleanisLastPage(StringcurrentPage){
273
returncurrentPage.equals(this.getNextPage(currentPage));
}
protectedStringgetNextPage(StringcurrentPage){
intindex=this.pages.indexOf(currentPage);
if(index==1)returnnull;
if(index==this.pages.size()1)returncurrentPage;
returnthis.pages.get(++index);
}
/**Thismethodiscalledfromwithintheconstructorto
*initializetheform.
*WARNING:DoNOTmodifythiscode.Thecontentofthismethodis
*alwaysregeneratedbytheFormEditor.
*/
//<editorfolddefaultstate="collapsed"desc="GeneratedCode">//GEN
BEGIN:initComponents
privatevoidinitComponents(){
buttonsPanel=newjavax.swing.JPanel();
cancelButton=newjavax.swing.JButton();
nextButton=newjavax.swing.JButton();
backButton=newjavax.swing.JButton();
jSeparator1=newjavax.swing.JSeparator();
titlePanel=newbr.inf.ufsc.lagar.swingutil.SimpleInternalFrame();
mainPanel=newjavax.swing.JPanel();
cancelButton.setText("Cancel");
cancelButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
cancelButtonActionPerformed(evt);
}
});
nextButton.setText("Next>");
nextButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
nextButtonActionPerformed(evt);
}
});
backButton.setText("<Back");
backButton.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(java.awt.event.ActionEventevt){
backButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayoutbuttonsPanelLayout=new
org.jdesktop.layout.GroupLayout(buttonsPanel);
buttonsPanel.setLayout(buttonsPanelLayout);
buttonsPanelLayout.setHorizontalGroup(
buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
buttonsPanelLayout.createSequentialGroup()
.addContainerGap(227,Short.MAX_VALUE)
.add(backButton,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,97,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
274
.add(nextButton)
.add(17,17,17)
.add(cancelButton)
.addContainerGap())
.add(jSeparator1,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,531,
Short.MAX_VALUE)
);
buttonsPanelLayout.linkSize(newjava.awt.Component[]{backButton,
nextButton},org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonsPanelLayout.setVerticalGroup(
buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LE
ADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
buttonsPanelLayout.createSequentialGroup()
.add(jSeparator1,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,10,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(buttonsPanelLayout.createParallelGroup(org.jdesktop.layout.Group
Layout.BASELINE)
.add(cancelButton)
.add(nextButton)
.add(backButton))
.addContainerGap())
);
buttonsPanelLayout.linkSize(newjava.awt.Component[]{backButton,
nextButton},org.jdesktop.layout.GroupLayout.VERTICAL);
titlePanel.setTitle("Wizard");
mainPanel.setLayout(newjava.awt.CardLayout());
org.jdesktop.layout.GroupLayoutlayout=new
org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonsPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.add(titlePanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,531,
Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,507,
Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup()
.add(titlePanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(mainPanel,org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,289,
Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonsPanel,org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
275
);
}//</editorfold>//GENEND:initComponents
privatevoidcancelButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_cancelButtonActionPerformed
this.cancelWizard();
}//GENLAST:event_cancelButtonActionPerformed
privatevoidnextButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_nextButtonActionPerformed
if(this.nextButton.getText().equals(FINISH)){
this.endWizard();
}else{
this.goNextPage();
}
}//GENLAST:event_nextButtonActionPerformed
privatevoidbackButtonActionPerformed(java.awt.event.ActionEventevt){//GEN
FIRST:event_backButtonActionPerformed
this.goPreviousPage();
}//GENLAST:event_backButtonActionPerformed
privatevoidendWizard(){
//TODOAutogeneratedmethodstub
privatevoidcancelWizard(){
//TODOAutogeneratedmethodstub
publicjavax.swing.JButtongetBackButton(){
returnbackButton;
}
publicvoidsetBackButton(javax.swing.JButtonbackButton){
this.backButton=backButton;
}
publicjavax.swing.JButtongetCancelButton(){
returncancelButton;
}
publicvoidsetCancelButton(javax.swing.JButtoncancelButton){
this.cancelButton=cancelButton;
}
publicjavax.swing.JButtongetNextButton(){
returnnextButton;
}
publicvoidsetNextButton(javax.swing.JButtonnextButton){
this.nextButton=nextButton;
}
//Variablesdeclarationdonotmodify//GENBEGIN:variables
privatejavax.swing.JButtonbackButton;
privatejavax.swing.JPanelbuttonsPanel;
276
privatejavax.swing.JButtoncancelButton;
privatejavax.swing.JSeparatorjSeparator1;
privatejavax.swing.JPanelmainPanel;
privatejavax.swing.JButtonnextButton;
privatebr.inf.ufsc.lagar.swingutil.SimpleInternalFrametitlePanel;
//Endofvariablesdeclaration//GENEND:variables
277
11 Apndice B - Artigo
278
Desenvolvimentodeumsoftwarepara
jogadoresdeloterias
EuclidesPinheirodeMelo
DepartamentodeInformticaeEstatsticaUniversidadeFederaldeSantaCatarina
(UFSC)
CaixaPostal47688040900SantaCatarinaSCBrasil
lagar@inf.ufsc.br
Abstract. Winninginalotteryhasalwaysbeenthedreamofmanypeople
sincetheearlydaysoflotterydrawings,whichstartedtotakeplacemany
centuriesago. At the same time, people have always been seeking ways to
improve their chances of becoming a winner, usually trying to discover
patternsthatmightbepresentinthepastresults,andputtingtheirbetsonthe
possibleresultsthatseemedtothemthemostprobabletooccur.However,both
thestatisticalanalysisofpreviousdataandthechoiceofacombinationofbets
satisfying some established criteria often implies in hard and repetitive
mechanicalwork,whichturnsouttobeevenworsewhenitbecomesnecessary
tofillalargenumberofbetcardsmanually.Withthisscenarioinmind,the
objective of this work is to supply a software that can help a wagerer to
formulateandlayhisbetswithoutwastingalongtimewithdulltasks,as
mentioned.
Resumo.Vencernaloteriatemsidoosonhodemuitaspessoasaolongoda
histriadahumanidade.Aspessoasvmconstantementecriandoeinventando
meiosparafazerosonhosetornaromaisprximoereal,eemgeral,estes
meiosexigem"trabalhobraal",comoarealizaodelongasanlisessobre
resultados passados, o desdobramento de apostas ou o preenchimento
manualdeumgrandenmerodecartes.Oobjetivodestetrabalhoconsiste
em fornecerumsoftwarequeauxilieojogador aterummeiodeprem
prticasuasidias,semprecisardispenderumlongoperododetempocom
tarefasmanuais,deixandooapostadorconcentrarsenapartequedemanda
maisinteligncia.
1.Oproblemadaloteria
Oproblemadasloteriasconsisteemdescobrirquedezenasserosorteadasnoprximo
concurso, ou que aposta, ou conjunto de apostas, ter acertado o maior nmero de
dezenaspossvelnoprximoconcurso.
Umfatoaceitoquenopossvelpreverexatamenteoprximoresultado,uma
vezqueumaloteriateoricamenteumsistemaaleatrio.Masissonoimpedeamente
humanadeimaginarmeiosdechegarperto,tentandoanalisarasvariveisqueesto
presenteseimaginarplanos,cenriospossveisparatentartomarumadecisomelhor.
Cada apostador tem sua grande idia nica de como resolver este problema. Por
exemplo,hosqueacreditamqueomelhormeioutilizarnmerospresentesnoseudia
adia,comoidadedosfilhos,nmerodedocumentos,entreoutros.Hquemacredite
que sonhar com os nmeros um bom meio. H quem acredite que produzir um
conjuntodecartescomdeterminadascaractersticasomelhormeio.Independenteda
validade destes meios, o que o usurio precisa, em muitos casos, de um suporte
ferramentalparapremprticaasuagrandeidianica.
nestecenrioqueentraumsoftwareparajogadoresdeloterias.Umsoftware
parajogadoresdeloteriasnoumacaixamgica,ondeapertaseumbotoeconsegue
seasdezenasqueirosairnoprximoconcurso.Talrecurso,apesardedesejvel,no
possveldeserconcebido,devidoanaturezadoproblema.Oqueumbomsoftwarepara
loterias pode fazer, para auxiliar o jogador, reunir as informaes disponveis e
permitir que o usurio possa visualizar elas de maneira agradvel (utilizandose de
interfacegrfica,dadossobaformadegrficos),auxiliandoasuatomadadedeciso
paraoprximoconcurso.Outracaractersticadeautomatizartarefasrepetitivas,que
podemserfeitasrapidamenteutilizandoseumcomputador,quesefossemfeitaspelo
homem,seriamtediosasepassveisdeerros.
2.Softwareparajogadoresdeloteria
Umsoftwareparajogadoresdeloteriastemcomopropsitoprincipalaliviarousurio
detarefasquenodemandaminteligncia,ouseja,tarefasmecnicaserepetitivas;eno
apenasaliviarousurio,comotambmdaragilidadeeconveninciaaoprocessodese
jogarnaloteria.
O processo de jogar na loteria, consiste, basicamente, nos seguintes passos
representadosnafiguraabaixo:
Figura1:processoparajogarnaloteria
Observandosecadapassodescrito,notasequeexisteumasriedeatividades
manuaisqueousurioprecisariaexecutar senousarumsoftwareparajogadorde
loterias.Vamosaalgumas:
Nocasodaanlise,emparticularderesultadospassados,teriaquemanualmente
colhertodososresultadosdeloteria,eaplicarmeiosdevisualizarestesdadosde
forma mais agradvel. Ex: visualizar a distribuio de pares e mpares nos
resultadospassados:colhercadaresultado,contaremcadaresultadoquantos
paresemparesderam,montarumatabelaougrficoexibindooresultadoda
anlise.Manualmente,maisdeumdiadetrabalho;
No caso de gerar, em particular em boles, onde se costumam jogar, por
exemplo,centenasoumilharesdevolantes.Enumerartodososnmerosdecada
volanteumtrabalhoextremamenterepetitivoedemorado;
Nocasodefiltrar,aplicarregrasderejeiteouaceiteemcadavolante,novamente
umtrabalhodemorado;
Nocasodemarcarvolantes,pintarcadacluladecadavolantedeloteriausando
canetaalgoquepodedediasasemanas,dependendodotamanhodojogo;
Nocasodeconferir,examinarcadacartoparadeterminaraquantidadedeerros
eacertos,nocasodehavermuitosvolantes,demandamuitotempoeesforo;
Emsuma,opropsitobsicodeumsoftwareparajogadoresdeloteriasconsiste
emautomatizarastarefasdescritasacima(podendoaindaofereceroutrasfacilidades
mais)edeixarcomojogadoraestratgiaqueelejulgueadequadaparavencer.Deste
modo,umsoftwareparajogadoresdeloteriavistocomoumaferramenta,algoque
promoveaeficincia,minimizaresforoparaaquelequetemdeexecutaralgumatarefa.
Umaanalogia:imaginequevocprecisapregarumpregonaparede.Voctemoprego,
voctemaparede.possvelserfeitoscomasmos,masoesforoetemposero
muitograndes.Atarefasetornamaisfcilquandovoctemumaferramentaadequada
paraoproblema:nocaso,ummartelo.Encareosoftwareparajogadoresdeloteriacomo
omartelo:teraferramentanogarantequeopregoestarpregado,masfacilitaatarefa.
Dependedoutilizadordaferramentaparaalcanaroobjetivo.
2.1Limitaes
comum,quandoaspessoasouvemsobresoftwaresdeloteria,pensarqueinventou
seumjeitogarantidodeganhar,ouentopensarqueosoftwarevaiganharparamim.
Osoftwareumaferramentaquevocusaparafacilitaravidaaojogarnaloteria,e
dependedaestratgia,deentradadousurioparafornecersada.
Aoacessarsitesdeprodutoscomerciaisdeloteria,comumanunciaremqueo
softwarevaitefazerganhar,masestejacientequetodosoftwaredestetiposofredesta
limitao,queaimpossibilidadedegarantirganhos(claro,possvelgarantirganhose
especificaralgunscenrios,maspensedemodogeral).
Outralimitaoestnofatodequeosoftwarenuncavaisatisfazer todosos
desejosdetodososjogadores:cadajogadortemsuaestratgianicaeparticularque
acha adequado para vencer na loteria. Os softwares disponveis renem algumas
estratgias comuns que boa parte dos jogadores gostam / costumam jogar e
disponibilizam no software. A falta de extensibilidade por parte dos softwares
disponveis tentar ser resolvida neste trabalho. Softwares existentes podem ser
encontradosnasreferncias[SPLOTO01],[PAPASORTE01]e[GERASORTE01].
3.Projetodosoftware
Osoftwarefoiprojetadoparasuportaroprocessoparajogarnaloteria.Utilizouseos
passosmacrodoprocessoparadividirosoftwareemmdulos,essencialmenteumpara
cadapasso.Soeles:
MduloncleoClasseseabstraescomunsusadasportodososmdulos;
MduloanliseClasseseabstraesrelacionadascomrequisitosdeanlise;
MdulofiltroClasseseabstraesrelacionadascomosrequisitosdefiltro;
Mdulo gerador Classes e abstraes relacionadas com os requisitos de
gerao;
MduloconfernciaClasseseabstraesrelacionadascomosrequisitosde
conferncia;
Mdulo impresso Classes e abstraes relacionadas com os requisitos de
impresso.
Arepresentaogrficapodeserencontradanafiguraabaixo:
Figura2:Representaodosmdulos
Estefoioprimeiroesforodedivisodoproblema,odetentarquebraroprojeto
desoftwareemunidadesmenoresdesoftware,parafacilitaracodificao,validao
dosrequisitosetestes.
3.1Casosdeuso
Para facilitar a visualizao das funcionalidades do sistema, segue abaixo o
diagramadecasosdeuso:
Figura3:Diagramadecasosdeuso
Novamente,oscasosdeusosotarefasqueestopresentesnoprocessoparase
jogarnaloteria.
3.2Tornandoosoftwareextensvel
Osistemausa,emvriosmdulos,anoodeumaarquiteturaplugin,nosentidoque
cdigonovointroduzidonorequermudanaemcdigoexistenteparaqueocdigo
existente perceba e possa fazer uso das novas funcionalidades adicionadas. Alguns
exemplosclssicos,parafacilitaroentendimento:
Navegadoresdeinternetsuportampluginsparaadicionar novos tratadoresde
tipo de mdia: por exemplo, o usurio instala o plugin do Macromedia Flash para
suportarestetipodemdianonavegador,eocdigodonavegadornoalteradoou
recompilado;
Editoresdeimagem,comooPhotoshop,Gimp,Corelsuportampluginspara
aplicarefeitosnasimagensemedio;
Ambientesdedesenvolvimento,comooEclipseeoNetbeans,permitemque
novasfuncionalidadessejamagregadasaoambiente.OEclipselevouoconceitoto
longe que o prprio software apenas um grande gerenciador de plugins, no
fornecendoeleprpriofuncionalidadedeuso.
Nocasodestesoftwaredeloterias,foiutilizadoesteconceitoparaqueoutros
programadorespossamadicionarnovasanlises,filtros,tiposdejogos,verificadorese
geradoressemprecisartocaremumanicalinhadecdigosequerdetodoosistema.
Isso facilitamuitoaadiodestasnovasfuncionalidades,poisquemassimoquiser
fazer,apenasprecisaescreverseunovocdigodeinteresse,semsepreocuparemcomo
tornarissodisponvelparaaestruturaexistente.Aestruturaexistentecapazdedetectar
quealgonovoestpresenteetratardeencaixlanocontexto.Destemodo,orequisito
de extensibilidadefacilitadaficagarantido,queumdosmaiores diferenciais deste
softwareemcomparaocomoutrossoftwaresexistentes.
4.Tecnologiasutilizadas
Comoestetrabalhodecdigoaberto,aescolhadastecnologiastemdelevareste
aspectoemconta,umavezquesehodesejodasociedadeempoderacessareeditar
este cdigo, h a preferncia queesteo seja feito usando tecnologias livres,ou no
mnimo gratuitas, para que, quem for manusear o fonte, possa instalar as mesmas
ferramentasqueodesenvolvedorprincipalutilizou.Seriaruim,imaginandoqueeufosse
umdesenvolvedornovo,querendoconhecereeditarocdigodoprojeto,tivesseque
comprarumaferramentacaraparapoderabriraestruturadeprojetodecdigoeeditar
osfontes.
Utilizousedasseguintestecnologias:
LinguagemJavaverso5[SUN01].
Netbeans5.5[NETBEANS01].
HospedagememSourceForge[SOURCEFORGE01].
5.LagarLottery1.0
LagarLottery foi o nome dado ao software. Por se tratar de um cdigo que est
disponvelemumrepositrioamericano(SourceForge)eestardisponvelparaomundo,
escolheuseumnomeeminglsparaoproduto(epor estemesmomotivoqueo
cdigofonteestemingls).
Ofonte,binrioedocumentocompletospodemserobtidosnositedoprojeto:
http://sourceforge.net/projects/lagarlottery
6.Consideraesfinais/trabalhosfuturos
Esteartigodemonstraqueumsoftwareparajogadoresdeloteriaumaferramentatil,
equeumaferramentadestanaturezapodesermuitointeressante,atparaquemno
costumajogarmuito.
Um grande desafio deste trabalho foi tentar contornar o problema da
extensibilidade:cadajogadortemsuaidianicaeparticulardegerarumjogo,realizar
umaanlise,filtrarcartes,emfim,cadajogadordeloteriatemasuagrandeidia,e
nopossvelpreverissodeantemo.Asoluoadotadanestetrabalhofoideixaro
softwarecomvriospontosdeextensibilidade(umemcadamdulo)paraqueojogador
pudesseelemesmo(setiverconhecimentodeprogramao)oupedirparaqueoutroo
faa(ocdigolivre)paraadicionarasuatoparticularfuncionalidade.Seosoftware
notivessesidoprojetadoparaterospontosdeextensibilidadeeusaraarquitetura
plugin,essatarefadeadicionarcdigonovoseriamuitomaisdemoradaepenosa.Mas
com essa soluo, uma nova anlise ou filtro pode ser adicionado em questo de
minutos.
Neste ponto temos uma possibilidade de trabalho futuro (verso 2.0) do
software: permitir a insero de cdigo novo (anlise, filtro, etc) atravs de uma
linguagemdescript,noestiloqueferramentasdeescritriocomooMicrosoftExcel
permite adicionar atravs de macros: o usurio poder, atravs de uma linguagem
simples,especificarumanovafuncionalidadeeexecutarestanovafuncionalidadeno
prprioambiente.
Outra possibilidade de trabalhofuturoest em capturar regras deanlise do
usurio,paraqueosoftwarepossa,atravsdestasregrasfornecidas,processarosdados
daanliseautomaticamente.Porexemplo:imaginequevocsempreolhaacaracterstica
Xdaanlisedeparesxmpares,procurandosempreporumpadroY.Sevocpudesse
dizerissoparaosoftware,estepoderiacoloriratabelaresultantecomcoresdiferentes
indicandoumpadrofornecido.
Por fim, deixo o convite a realizar o download do projeto em
http://sourceforge.net/projects/lagarlottery/ ,experimentarosoftwareecontribuircom
suas idias e cdigo para que este seja um dos melhores entre os softwares para
jogadoresdeloteriasexistentes.
Referncias
[SUN01] Linguagem java. Disponvel em: http://java.sun.com. Acesso em: abril de
2006.
[NETBEANS01]NetbeansIDE.Disponvelem:http://www.netbeans.org.Acessoem:
abrilde2006.
[SOURCEFORGE01]SourceForge.Disponvelem:http://sourceforge.net/.Acessoem:
abrilde2006.
[SPLOTO01] SpLoto. Disponvel em: http://www.spolti.com.br/sploto/. Acesso em:
maiode2006.
[GERASORTE01]Gerasorte.Disponvelem:http://www.gerasorte.com.br/.Acessoem:
maiode2006.
[PAPASORTE01] Papasorte. Disponvel em: http://www.loteria.com.br/. Acesso em:
maiode2006.