ads

segunda-feira, 1 de dezembro de 2008

Óptimo site sobre viagens!

Visitem o recém inaugurado site sobre viagens pelo mundo!

http://viajantesmundo.blogspot.com/


O objectivo do http://viajantesmundo.blogspot.com/ é auxiliar a todos que desejam viajar ao redor do mundo, mantendo o viajante bem informado.

A estrutura do site é a seguinte:
-> Do lado direito encontram-se links patrocinados pelo Google, que oferecem os produtos e serviços que melhor lhe atendem.
->Logo abaixo dos anúncios, há uma lista de blogs recomendados e um pouco mais abaixo uma imagem diferente e surpreendente fornecida diariamente pelo National Geographic POD!
-> Abaixo do campo de mensagens postadas há um textfield com notícias de vários países do mundo (temas como economia, política, esportes, viagem e imigração, empresas, etc) . Abaixo há mais uma propaganda.

Click e confira!

domingo, 16 de novembro de 2008

Cases de Sucesso de Empresas que optaram por Arquiteturas Orientadas por Serviço (SOA)

1. Comcast
Uma das maiores (se não a maior) operadora de TV a cabo dos EUA. Eis a sua abordagem:
Se preocuparam inicialmente com a arquitetura e não em comprar ESB
Depois de desenvolver a arquitetura, o foco foi o framework de governança para implementação e gestão dos novos serviços
Direcionou os esforços iniciais de SOA para o legado (e.g. billing)
Tempo de maturação do projeto: 18 meses
Lições aprendidas: “…a Comcast deveria ter desenvolvido um modelo de serviço de dados comum depois de definir a arquitetura. Sem serviços de dados padrões para acessar informação corporativa e gerenciar interações entre sistemas, os desenvolvedores acabaram projetando seus serviços para executar o trabalho de diferentes maneiras, o que gerou inconsistências, quebrando a promessa de SOA de possibilitar um mix fácil de componentes de serviços“


2. Leapfrog
Uma das mais conhecidas fabricantes de brinquedos educativos.
Cenário: vários sistemas e soluções em Java 5 e 6, C# da Microsoft e web services com diversas bibliotecas de terceiros
Objetivo: maior reutilização de código, desenvolvimento mais veloz e integração mais fácil; mas a empresa não queria limitar a iniciativa SOA a uma mudança da guarda de ferramentas de desenvolvimento e plataformas de integração
Abordagem: POJO, ESB Open-source (Mule), utilização de 2 (dois) ESBs - um para gerenciar fluxo de dados e outro para aplicações Web (Portal do cliente)
Por que o Mule? “…porque sua única tarefa é gerenciar mensagem. Todos os fornecedores comerciais queriam nos vender um pacote completo de produtos. Mas o ponto principal de SOA é passar de um sistema fechado para outro’…“, afirma o diretor de infraestrutura de sistemas


3. United Airlines
Grande empresa aérea dos EUA, companhias aéreas, assim como empresas de Telecom, de Finanças etc, tem muitas tarefas baseadas em eventos. É neste ponto que entra a EDA (Event-driven Architecture).
Histórico: a United investiu há tempos em EDA, usando o WebSphere da IBM como barramento de mensagem por sete anos. Em 2006, deu início a uma implementação SOA para lidar com os web services modernos usados no web site United.com.
Precisa conviver com estes 2 ambientes (EDA e SOA)
Desafio: projetar e implementar serviços em uma empresa que tem duas arquiteturas e necessita de ambas
Problemas que tiveram com ESB: “ESBs não utilizam padrões fora dos padrões de web services”, afirma o gerente de middleware da United
Por que o ESB é tão importante? a United “...valoriza o uso de ESBs para SOA e EDA porque eles lidam com mensagem, transformações de dados e outras tarefas críticas de roteamento de dados….“
Experiência com EDA+SOA: falta de esquemas XML padrões para EDA, fazendo com que a transferência de mensagens entre serviços EDA e SOA seja mais complexa e demande mais pessoal.


4. Thomson Financial
Empresa de serviços de informações financeira (também uma das maiores do mundo).
Lições aprendidas: “…Um grande número de empresas aprecia o conceito de SOA porque ele promete acelerar o desenvolvimento. Mas alguns desenvolvedores descobriram que um elemento-chave da governança de serviço, na realidade, pode retardar o desenvolvimento, roubando a velocidade prometida. “
Serviços: muitos (milhares) com om alta granularidade, baixa granularidade — com tudo que pode haver entre os dois — e uma equipe de arquitetura pequena
Solução: recorrer à automação utilizando ferramentas de avaliação de políticas da WebLayers. “As ferramentas são mais eficientes e não deixam passar violações”, diz o VP de serviços de gerenciamento de produto


5. Jabil
A Jabil é uma grande empresa de manufatura (monta circuitos, impressoras, computadores etc).
Desafio: integração do cliente – por exemplo, sistemas de billing, previsão e entrada de pedidos e os muitos sistemas utilizados por seus clientes; é muito difícil gerenciar toda esta comunicação ponto-a-ponto à medida que a base de clientes cresce e evolui os próprios sistemas
Arquitetura anterior: baseada em “hubs” de integração para trocar informações com seus mais de 5.000 parceiros. Resultado: muita dificuldade para manter manualmente todas as interfaces
Solução: adotou princípios SOA para substituir a maioria destas conexões personalizadas por conexões baseadas em serviços que possibilitam a reutilização de funções comuns
Produto/Abordagem de implantação: Ao invés de usar um ESB para gerenciar mensagens, um registro para gerenciar o repositório de serviços ou um ambiente de desenvolvimento orientado a SOA para desenvolver os serviços, a Jabil emprega o Gentran Integration Suite da Sterling Commerce para as três finalidades. O pacote é projetado para interações do supply-chain.

domingo, 12 de outubro de 2008

Passo a passo com EJB 3.0 – Enterprise JavaBeans

Objetivos do Tutorial:

Ajudar no desenvolvimento das primeiras aplicações, utilizando EJB 3.0.
Indicar uma sequência de passos a serem seguidos a fim de compreender os
principais mecanismos oferecidos por esse framework.

Passo 1: Configurar o Ambiente

Jboss AS 4.0.4 instalado com perfil EJB 3.0 (http://labs.jboss.com/jemsinstaller/, baixar o arquivo: 1.2.0.GA)
Eclipse SDK, versão 3.2 http://www.eclipse.org/downloads/
PostgreSQL, versão 8.2 http://www.postgresql.org/download/
Driver do PostgresSQL http://jdbc.postgresql.org/download.html, baixar arquivo
JDBC3)

Passo 2: Contruir Projeto

Crie um Java Project. Modifique o Build Path do projeto para referenciar as APIS do JBOSS que estão no diretório jboss-4.0.5.GA \ client.

Passo 3: Construir Entidade

import javax.persistence.Entity;
import javax.persistence.Id;

@ Entity
public class Curso implements Serializable {

@ Id
@ GeneratedValue
private Integer cod;
private String nome;
/ /.. getters e setters omitidos
}

Essa entidade utiliza anotações presentes na bibliteca do JPA, Java Persistence API. A anotação @ Entity define a classe como persistente.

Os cursos serão persistidos na tabela? curso? na base de dados, pois por default o JPA considera o nome da classe igual ao da tabela. a anotação @ Id define o atributo cod como o identificador da tabela no banco de dados a anotação @ GeneratedValue define que o valor do atributo cod será gerado automaticamente no momento em que os objetos forem persistidos.


Passo 4: Construir Interface

import javax.ejb.Local;
import javax.ejb.Remote;

@ Remote
public interface Cadastrar {

void cadCurso (Curso curso);
Collection getCursos ();
}

Características de EJB 3

Antes de criar o Session Bean, é preciso definir suas interfaces de acesso. Um Stateless Session Bean, definido no próximo passo, pode ter uma interface local e remota.

Nesse exemplo, a interface é remota. A anotação @ Remote define essa interface como Remota, oferecendo acesso a clientes remotos. Para declarar uma interface como Local? que não oferece acesso a clientes remotos, deve ser utilizada a anotação @ Local. Esse tipo de interface deve ser usado para clientes localizados na mesma JVM onde está rodando o container de EJBs.


Passo 5: Construir Session Bean



import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@ Stateless
public class CadastrarBean implements Cadastrar {

private List cursos;

@ Persistence
Context EntityManager entitymanager;

public CadastrarBean () {

cursos = new ArrayList ();

}

public void cadCurso (Curso curso) {

entitymanager.persist (curso);

}

public List getCursos () {

cursos = entitymanager.createQuery (" select * from CURSO "). getResultList (); return cursos;

}

}


Características de EJB 3
O Session Bean representa um cliente no servidor J2EE. Para acessar a aplicação, o cliente invoca os métodos do Session Bean. É similar a uma sessão interativa, sendo único para cada cliente. Assim como a sessão, os dados do bean não são armazenados em uma base de dados. Quando o cliente encerra a sessão, o session finaliza e não ficará mais associado a ele.


Existem dois tipo de Session Bean: Stateless e StateFul. A anotação @ Stateless define a classe CadastrarBean como sendo do tipo Stateless. É mais leve e indicado para processos que não necessitam manter estado (valores de atributos) durante as chamadas de métodos. Para definir o tipo Stateful, é necessário atribuir a anotação @ Stateful. Esse bean é mais pesado, mas garante a preservação do estado entre as chamadas de métodos de um mesmo cliente.

A anotação @ PersistenceContext, da API de JPA, possibilita o processo de injeção de dependência. O container EJB reconhece a anotação e, automaticamente, injeta um objeto EntityManager na propriedade.

Passo 6: Contruir os arquivos de configuração

Vejamos o arquivo persistence.xml

xmlns: xsi = " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = " http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

java: / CursoDS

Esse arquivo deve ser inserido na aplicação, no diretório META-INF / persistence.xml. O elemento deve estar associado ao elemento do arquivo curso-dx.xml, explicado abaixo.

Vejamos o arquivo curso-ds.xml

CursoDS jdbc: postgresql: / / localhost: 5432 / curso org.postgresql.Driver
postgres
postgres
PostgreSQL 7.2

Esse arquivo deve ser inserido dentro do diretório server \ default \ deploy do JBOSS.

Nesse arquivo, são configuradas as propriedades referentes à conexão com o banco de dados PostgreSQL. O nome CursoDS configurado através do elemento está associado ao elemento, mencionado no arquivo de configuração citado anteriormente.

Passo 7: Deploy do projeto

Após ter criado o projeto, exporte para arquivo. jar dentro do diretório jboss-4.0.5.GA / server \ default \ deploy do JBOSS. Repare que é o mesmo local onde fica armazenado o curso-ds.xml.

Inicie a conexão com o PostgreSQL e crie um banco de dados com o nome curso.
Coloque o driver do PostreSQL no diretório jboss-4.0.5.GA2 \ server \ default \ lib do JBOSS. Inicie o JBOSS e confira se o projeto foi deployado. Confira se a tabela curso foi criada no seu banco.

Passo 8: Construir o Cliente

Crie no mesmo projeto a classe abaixo:

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

public class Cliente {

public static void main (String [] args) throws Exception {

Hashtable prop = new Hashtable ();
prop.put (InitialContext.INITIAL_CONTEXT_FACTORY, " org.jnp.interfaces.NamingContextFactory ");
prop.put (InitialContext.PROVIDER_URL, " jnp: / / localhost: 1099 ");

Context ctx = new InitialContext (prop); Cadastrar cad = (Cadastrar) ctx.lookup (" CadastrarBean / remote ");

Curso curso = new Curso ();
curso.setNome (" AJAX ");
cad.cadCurso (curso);
curso.setNome (" XML ");
cad.cadCurso (curso);
curso.setNome (" PROGRAMAÇÃO ");
cad.cadCurso (curso);

for (Curso c: cad.getCursos ()) {
System.out.println (c.getCod () +? -? + c.getNome ());
}
}
}

Características de EJB 3

É necessário realizar a conexão com o serviço de nomes, através de um objeto InitialContext da API JNDI (Java Naming and Directory Interface). Através desse objeto, é possível obter um referência para o objeto remoto.

Nesse exemplo, o contexto deve ser inicializado por meio de um objeto HashTable. Caso a aplicação fosse construída utilizando um mesmo container, o contexto seria único e conhecido.

Então, não seria necessário especificá-lo, possibilitando a inicialização do objeto InitialContext sem parâmetros. Através do método ctx.lookup (" nome-da-clase / remote "), um Session Bean remoto é solicitado ao container.

Passo 9: inicializar o Cliente

sábado, 6 de setembro de 2008

Hands on with Google Chrome Beta

Hands on with Google Chrome Beta

Make no mistake: Google's new Chrome Web browser beta is a shot directly across Microsoft's bow, and the most obvious statement yet by Google that it intends to take on the software giant in new and potentially earth-shattering ways. Back in the mid-1990's, we were treated to the somewhat humorous notion that Netscape's Web browser would someday evolve into a platform that would threaten Windows. For its part, Microsoft took that possibility so seriously that it wiped Netscape right off the map, using tactics that some would charitably describe as illegal.


This time around, though, there's no joke. Cloud computing is a reality, and for a growing generation of users, computing is something that happens online and, increasingly, with mobile devices instead of traditional PCs. And Google's right there in the thick of things, not just with Chrome, but also with a suite of Web products and services and, soon, the Android mobile platform. This is what's known as a wakeup call in the industry. And Microsoft, that phone is ringing for you.


I'm not going to get into a debate about cloud computing right now. I think so much of this phenomenon, however, that I've raised it to first-class status on this site, alongside such staid and traditional Microsoft topics as Windows and Office. So take that for what it's worth.


And no, I'm not going to get into broader opinions about whether Google Apps is viable competition for Microsoft Office, or whether you should use Live Search instead of Google Search. No, this time I'd like to focus on a very simple and singular topic, the Google Chrome Beta, and whether it works as advertised.


If you're interested in my opinion about the why's of Chrome, fear not, I can't shut up about that either. I wrote the first lengthy overview of the browser anywhere (sorry Mr. Mossberg), a full day before it was released, in my Google Chrome Preview. And I've written two WinInfo news articles, Google to Launch its Own Web Browser ... Today, and Google's Browser Created Out of Fear of Microsoft, that pretty much sum up my feeling about why Google is really doing this.


Whatever, right? Google's browser is here. We can use it, look at it, and evaluate it. And I have to tell you, so far, I like what I see.



General thoughts


One of the things that's quite striking and obvious about Chrome is how stripped down it is from a visual standpoint. It's like a 1.0 Apple product in this way: What's there works wonderfully but you very quickly find yourself wondering where some pretty obvious features went. This simplicity extends from the Setup routine--which if anything is too simple; you can actually miss out on some important choices if you're not careful--to the browser UI itself, which dispenses with most of the busyness that dogs other browsers. There's no menu bar or status bar at all, and whatever UI there is just fits in a single horizontal row by default. Google has compared the uncluttered Chrome UI to that of its Web search page, and fair enough. There's a certain consistency there, and if you value that sort of thing, Chrome will be instantly appealing.



Google says that the point of the UI minimalism is to get the browser out of the way so you can focus on whatever Web application, site, or service you're using. This, too, is believable and mostly effective, though I'd also point out that I never really thought of the Firefox UI as being distracting or busy, and of course I pare that browser UI down as well myself. (That's one of the nice things about a product as malleable as Firefox, I guess. It can be simple or complex, your choice.)


Chrome looks equally at home in both Windows XP and Vista. I like that. And it's one part of the UI that I think Mozilla really screwed up with Firefox 3 (see my review). Despite an apparent effort to make that browser look native in each OS, I think it just looks different. Chrome, somehow, seems to disappear into Windows in a very pleasing way. It's a sharp looking browser.


I'd also point out from a general browsing standpoint that Chrome doesn't suffer from the level of Web site incompatibility that does Internet Explorer 8 Beta 2 (see my review). Yes, I get that the WebKit rendering engine is mature and modern and all that, but come on: Did anyone really think that a Google browser would be more compatible with the Web than the next version of the most compatible browser there is? I'm shocked by this, and though I know I'm going to get dozens of emails from people complaining about specific sites not working properly with this browser, in my experience, it's been very compatible. Much more so than IE 8 Beta 2.



Tabs


If the Chrome user interface has a single unique feature, in my mind it's the focus it puts on tabs. Yes, other browsers have had tabs for years, but Google has put its tabiness (ahem) up front and center, and there are a number of unique capabilities that result.


First, the row of tabs is visually located above the other browser controls, like the Back and Forward buttons, and the address bar (which is actually called the omnibox; see below). Big deal, you're thinking; it's just in a different place. Actually, this subtle change means that each tab has its own set of controls. And all of the things that are associated with that tab--including your browsing history--travel with the tab.


And travel they can. While other browsers offer a way to drag and drop tabs within a single window, Google takes this capability a step further by letting you drag tabs onto the desktop, to create a new window, or onto other windows. Chrome does lack the nice tab grouping and coloring feature that adorns IE 8 Beta 2, however.



Tabs aren't just about looks either. As is the case with IE 8 Beta 2, tabs in Chrome all run within their own process, so they essentially work and act like individual applications in Windows. In older browsers, the entire browser window was a single process. So if something in one tab crashed, the whole browser crashed. Mozilla sort of fixed this problem by creating a browser recovery feature for Firefox. But Microsoft and Google have really fixed it by not letting errant Web content in one tab bring down the whole browser.


Google thinks so much of tabs that the default home page, such as it is, is sort of like a Web search results page that shows you the pages you've visited most frequently. The notion here is that most people visit the same places over and over again, so this page should prove worthwhile for many users. I'm still unsure about it, but since my traditional home page is one of the "results," I will try to make it work. From a presentation standpoint, this default home page is laid out with two major sections. On the leftmost three quarters of the page is a grid of Web page thumbnails, similar to the Quick Tabs view in IE 7 and 8, where each thumbnail is of a page you've visited frequently and recently. On the right is a text column with a search box and recently bookmarked pages.



Omnibox


Instead of sporting a separate address bar and search box, Google Chrome combines them into a single, unified box that does it all. Dubbed the "omnibox," this uber address bar lets you manually type in Web addresses, of course. But it also provides Web search functionality, access to your Web history, live suggestions, and more. It should be noted that both Mozilla, with Firefox 3, and Microsoft, with IE 8 Beta 2, have made recent advances with their address bars. But Google is the first to combine the address bar with the search box, a move that, in retrospect, seems somewhat obvious.



And it works. You can select the omnibox in all the usual ways--with the mouse, via the ALT+D and CTRL+L shortcuts, and so on--and then just start typing. If you type a Web address, the omnibox will handle that, of course, and will auto-complete via drop-down, as with other browsers. Type in a non-URL and you can search Google--or, get this, the search engine of your choice--directly from the omnibox. I like it.


Tip: If you tap CTRL + K (the keyboard shortcut in Firefox for selecting the search box) or CTRL + E (the keyboard shortcut in IE 7/8 for selecting the search box), the Omnibox will be selected and the characters "? " will be added, allowing you to type in a search query. Nice.



Bookmarks


Most browser makers seem a bit obsessed with bookmarks (or, in IE lingo, favorites). Witness Mozilla's machinations with the Places/Library/Organize Bookmarks feature in Firefox 3 (seriously, what's the name, really?) and the spastic number of locations from which you can access favorites in IE 8 (Favorites Menu, Favorites Bar, Favorites Center) for obvious examples.


I find bookmarks annoying because I use so many different PCs, and the notion of saving a list of favorite links on individual PCs seems a bit too 1990s for me. (There are ways to save bookmarks online in a central location to overcome this problem, but I simply forego bookmarks, choosing instead to use a Web-based home page that has links to all the sites I need regularly.)


Anyhoo, Google, too, doesn't seem very concerned about bookmarks. By default, there's no mention of bookmarks in the Chrome user interface at all. However, if you imported bookmarks from another browser, you'll see a pretty tame Bookmarks bar below the browser control strip. (You can also enable it manually.) And as with Firefox, you can bookmark any page by clicking a star icon in the address bar/omnibox. And that's about it.



Google says they're working on a better bookmarks management system. But honestly, I think they should give it time and think about providing a centralized Web-based system for managing bookmarks instead of hard-coding it into the browser. This will keep the browser simple for those that don't need this feature, and provide excellent functionality for those that do. Plus, they could use Gears to provide offline access.



Web applications


Mozilla created a technology called Prism that allows you to take a Web application like Gmail, Google Calendar, or whatever, and save a shortcut to it on your Windows desktop. When you click such a shortcut, it loads the Web application in a minimal browser window that has no controls whatsoever, giving you a pseudo-local-application experience. Combined with offline technologies like Google Gears, these "best of both worlds" solutions can bridge the gap between the Web and Windows, and cloud computing advocates believe they will make it easier for consumers to adopt Web solutions during this transitionary period.


Google builds this capability into Chrome though it should be noted that you'll still need some sort of back-end offline functionality to make a Web application work like a true desktop application. All you need to do is visit a site (like Gmail) and choose Create application shortcuts from the Control button (which appears to the right of the omnibox). Chrome can create three shortcuts for any Web app, one each in the Start Menu, Desktop, and Quick Launch toolbar.


The effect is nifty and, again, much like that achieved with Prism. Each application shortcut maintains its own window dimensions, as well, just like a real application. And because Chrome is Gears-enabled, any Web applications that do take advantage of that technology can be used offline. The poster child at this time is Google Reader, Google's Web-based RSS reader.




Reliability


I haven't been using Chrome long enough to provide any meaningful opinions about its reliability, but I will make two observations. First, it's been rock solid on two different machines, and it's never crashed. Secondly, in the same time period after having installed IE 8 Beta 2, I did experience some crashes. Take those as the unscientific observations that they are.


In addition to the previously-described tabs-as-a-process feature, Google does provide a task manager (which is curiously similar to the Windows task manager) and, for "geeks" (read: Web developers), an About Memory page that provides more detailed information. You can use the task manager to kill errant tabs, but again, I've had no call to do so yet.


Tip: If you type about:% in the Chrome address bar/omnibox and hit Enter, you'll crash the whole browser. So much for tab process isolation.


Security features


Google Chrome provides a number of safety features, such as protection against malware hosts and phishing sites. In use, this functionality works much like similar features in Firefox 3 and IE 7/8, where you'll see a red page warning you of the problem.


Like IE 8 Beta 2, Chrome also features a special privacy browsing mode, which Google calls Incognito. (I like Microsoft's name for this feature, InPrivate, better.) Icognito launches as a separate browser window that features a few visual differences from a standard Chrome window, including a weird little spy character in the upper-left of the window. (He looks a little too much like the logo for


When you browse with an Incognito window, nothing you do is saved by the browser after you close the window. That means such things as cookies, Web history, and search history will all be erased. So it's perfect for when you want to secretly buy a present for your wife. Or, yes, browse porn.



Downloading


Google's no-nonsense file downloading functionality comes at an interesting time for me because I was just experimenting with turning off the download manager in Firefox 3 and allowing downloads to occur in the background, using just status bar-based notifications to let me know how things were progressing. Put simply, this is how Chrome works by default. It offers no visible browser manager by default. Instead, when you trigger a download, a small pop-up status bar-type display appears at the bottom of the current tab, noting the name of the download and, while it's downloading, it's progress. On the right is a Show all downloads link that will display a whole page showing every download you've performed, but there's no pop-up window as with most browsers.




Some people will take exception to this, and my guess is that download managers are one of the number one add-ons for IE, which lacks such functionality. But I really like Google's minimalism here. And I think you will too if you give it a chance.



Moving from your old browser


Google makes it easy to switch from your current browser to Chrome, assuming your current browser is IE or Firefox (which it probably is; over 95 percent of Web surfers use either browser). You can import bookmarks, search engine preferences, saved passwords, and browsing history from your default browser during install, though you'll miss it if you're not paying attention. (You can also import this data after the fact using a link in the Customize menu.) I actually did miss this the first time around and was surprised to see Chrome seamlessly access one of my password-protected sites. Yikes.




Final thoughts


Obviously, there's a lot more going on here, but it's early yet and we'll have to see how Google improves this thing over time before rendering any meaningful judgment. My initial off-the-cuff reaction to Google Chrome, however, is quite positive. It seems fast and efficient, and while it certainly works well with Google's Web applications, it also appears to work just fine with the rest of the Web that I visit regularly. If you're a heavy Google user like me, Chrome is no-brainer, you're going to love it. Otherwise, you should still try it: It doesn't break half the Web like IE 8, certainly, and installing it doesn't preclude you from continuing to use IE or Firefox, or any of the other browsers out there.


Is Google Chrome the future of the Web? You know, it just might be. So far so good.



Source: winsupersite

Aprenda a usar a JList Java



JList


JList é um componente gráfico de interface com o utilizador que apresenta uma lista de escolhas para selecção.
Pode ser efectuada selecção simples ou selecção de múltiplos itens.

Uma JList não suporta directamente a adição ou remoção de elementos depois de criada. Para criar uma lista dinâmica é necessário usar um ListModel. Existe um método de conveniência aplicável a objectos JList, setListData(), que permite alterar o conteúdo total de um objecto JList.

Criação de um objecto JList:

String [] opcoes = { “Opcao 1”, “Opcao 2”, . . . “Opcao N” }
JList lista = new JList(opcoes);

Métodos:

setVisibleRowCount(int nRows) – coloca o número de linhas visíveis.
Por omissão são 8 linhas visíveis.

JScrollPane scrollLista = new JscrollPane( lista);
Para aparecerem barras de scroll automaticamente se a lista contém mais itens que o número de linhas visíveis.

Uma Jlist gera eventos do tipo ListSelectionEvent através de um objecto ListSelectionListener.
O método invocado é:
public void valueChanged(ListSelectionEvent e )

Um objecto ListSelectionListener previamente registado numa JList pode ser notificado da ocorrência de 3 eventos diferentes (o objecto representativo do evento é sempre um ListSelectionEvent):
1. Um para a des-selecção do item seleccionado previamente (quando se prime o botão do rato noutro item),
2. Um para a notificação que a selecção se está a mover (quando se arrasta o rato entre itens), e
3. um para a selecção do novo item (quando se liberta o botão do rato em cima de um item diferente do anteriormente seleccionado).

O método getValueIsAdjusting aplicado aos dois primeiros eventos retorna true, e ao último retorna false.
Para retornar que item ou índice foi seleccionado pode-se usar os métodos da classe JList:
getSelectedValue()
getSelectedIndex()


Um objecto JList pode ser configurado de modo a permitir diferentes modos de selecção.
A selecção pode ser simples (só sendo possível seleccionar um item), pode ser de um único intervalo (só se podendo seleccionar um único intervalo de itens contíguos), ou de múltiplos intervalos (podendo-se neste caso seleccionar intervalos disjuntos).
A definição do modo de selecção, assim como a determinação dos itens seleccionados são efectuados através de um objecto ListSelectionModel associado ao objecto JList.

Para a lista suportar múltipla selecção deve-se usar o método:
public void setSelectionMode( int mode), em que mode pode ser um dos seguintes valores :
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

Os métodos
getSelectedValues()
getSelectedIndices()
permitem obter um array das selecções.




Construtores:

public JList ()
public JList (Object [] data)
public JList (Vector data)
public JList (ListModel modelo)


Métodos JList úteis:

· public void clearSelection()
· public int getSelectedIndex()
· public int [] getSelectedIndices()
· public Object getSelectedValue()
· public Object [] getSelectedValues()
· public int getSelectionMode()
· public void setSelectionMode( int mode )
valores possíveis:
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
· public int getVisibleRowCount()
· public void setVisibleRowCount ( int rows )
· public boolean isSelectedIndex( int index )

Métodos ListSelectionEvent úteis:

· public boolean getValueIsAdjusting()

sábado, 16 de agosto de 2008

Microsoft Virtual Earth será integrado aos serviços online do ArcGIS

A Microsoft e a Esri anunciaram esta semana que os usuários do ArcGIS terão acesso ao conteúdo de mapas e de imagens fornecido pela plataforma Microsoft Virtual Earth, dentro do ArcGIS Desktop e do ArcGIS Server.

Com o Virtual Earth integrado ao ArcGIS 9.3 Desktop, os usuários de ArcGIS podem agora facilmente adicionar a base de mapas para criar, editar, analisar e publicar dados.

Juntos, o Virtual Earth e o ArcGIS Online permitirão aos clientes acesso aos recursos que otimizarão seus projetos. A integração do Virtual Earth no sistema ArcGIS tornará mais fácil para os usuários de ArcGIS oferecer a seus clientes finais soluções mais acessíveis.

Os serviços de mapa do ArcGIS Online Virtual Earth abrangem mapas de ruas de alta resolução, imagens de satélite e fotos aéreas. Os mapas de ruas contêm mais de 60 países e regiões, incluindo América do Norte, Europa, América do Sul, Ásia e norte da África.

Planejamento urbano, geomarketing, análise de crime e gestão de redes são apenas alguns exemplos de como os usuários de ArcGIS Desktop, incluindo os de ArcGIS Explorer, podem otimizar os serviços de mapas com o ArcGIS Online Virtual Earth. Os usuários de ArcGIS Server poderão se conectar aos serviços de mapas do Online Virtual Earth em breve por meio de um service pack.

Os usuários podem pré visualizar os mapas de ruas e as imagens no link abaixo:
http://resources.esri.com/arcgisonlineservices 

+Informações
www.esri.com/arcgisonline

Revista Mundogeo