Customizing the IBM Sametime Business Card: Difference between revisions

From Wiki
(Created page with "I migrated the article "Customizing the IBM Sametime Business Card" from IBM developerWorks, after the sale of Sametime to HCL. =Summary= Having access to information about coworkers in day-to-day work should be quick and easy. This article describes, in a practical way, how to make such information available through the IBM Sametime Connect Client and the IBM Sametime Web Client (Sametime Proxy Server). =Introduction= Our story begins with a multinational company th...")
 
Line 88: Line 88:
Despite the ease of using the Sametime Administration Console, we are limited to the available fields. Moreover, not all user information is stored in a single repository, such as an LDAP directory, due to performance reasons. For example, user photos.
Despite the ease of using the Sametime Administration Console, we are limited to the available fields. Moreover, not all user information is stored in a single repository, such as an LDAP directory, due to performance reasons. For example, user photos.


== 1.2. O subsistema de Cartão de Visita ==
== 1.2. The Business Card Subsystem ==


O subsistema de Cartão de Visita do IBM Sametime busca as informações dos repositórios configurados no arquivo UserInfoConfig.xml.
The Business Card subsystem of IBM Sametime retrieves information from the repositories configured in the UserInfoConfig.xml file.


Estes repositórios podem ser:
These repositories can be:


* Um diretório LDAP
* An LDAP directory
* Um aplicação Notes
* A Notes application
* Uma classe Java, que por sua vez busca informações em uma base SQL ou em um ERP/SAP.
* A Java class, which in turn retrieves information from a SQL database or an ERP/SAP system.


A interface (API) que faz acesso a esses repositório que é chamada de BlackBox.
The interface (API) that accesses these repositories is called the BlackBox.


O processo de busca das informações pelo Cliente no repositório é descrito abaixo:
The process of retrieving information by the Client from the repository is described below:


1) o Cliente Sametime faz uma requisição HTTP (GET) a um servidor Sametime Community.
# The Sametime Client makes an HTTP (GET) request to a Sametime Community server.
 
# When the request reaches the Sametime/Domino HTTP server, Domino redirects the request to the UserInfoServlet servlet.
2) Quando a requisição chega no servidor HTTP do Sametime/Domino, o Domino redireciona o request para o servlet UserInfoServlet
# The UserInfoServlet servlet reads the UserInfoConfig.xml file, which contains the connection information for the repositories.
 
# The servlet queries each repository to retrieve the information.
3) O servlet UserInfoServlet, por sua vez lê o arquivo UserInfoConfig.xml, a qual tem as informações de conexão aos repositórios.
# The data from the repositories is returned to the UserInfo servlet.
 
# The servlet combines the responses from these repositories and converts them into an XML document.
4) O servlet consulta cada repositório em busca das informações
# The HTTP server sends the XML document to the client, which extracts the data and displays it on the client.
 
5) Os dados dos repositórios são retornadas ao servlet UserInfo
 
6) O servlet combina as respostas destes repositórios e converte em um documento XML.
 
7) O servidor HTTP envia o documento XML para o cliente, que extrai os dados e apresenta no cliente.


[[File:SametimeCustomizando03.png]]
[[File:SametimeCustomizando03.png]]


Figura 3: Configuração do Cartão de Visita no Sametime System Console
Figure 3: Business Card Configuration in the Sametime System Console


== 1.3. Adicionando atributos através do UserInfoConfig.xml ==
== 1.3. Adicionando atributos através do UserInfoConfig.xml ==

Revision as of 12:44, 15 August 2025

I migrated the article "Customizing the IBM Sametime Business Card" from IBM developerWorks, after the sale of Sametime to HCL.

Summary

Having access to information about coworkers in day-to-day work should be quick and easy. This article describes, in a practical way, how to make such information available through the IBM Sametime Connect Client and the IBM Sametime Web Client (Sametime Proxy Server).

Introduction

Our story begins with a multinational company that, a year ago, made IBM Sametime and IBM Connections available to its employees. Today, thanks to these two tools, employees communicate better and more effectively.

One morning, the company’s IT Director returns from a meeting with the Vice President of Marketing. The Marketing Department requested that new information be displayed in the IBM Sametime Business Card.

The IBM Sametime Connect Client and Web Client Business Card displays information about a contact, including Name, Title, Telephone, and even Photos. Users view this information when they are in a Chat window or when they hover the mouse pointer over a contact in the Contact List.

ADD SCREENSHOT WITH BUSINESS CARD

Figure 1: Business Card Screen

The IT Director challenges the IBM Sametime Administrator to meet the following requirements:

1. Add new fields from LDAP;

2. Add fields from the Company’s HR System;

3. Display the user’s photo stored in the IBM Connections Profile;

With these needs in hand, the IBM Sametime Administrator begins the customizations.

1. Adding New Fields from LDAP

By default, the configuration interface of the Sametime System Console Business Card allows you to select which information will be displayed in the Sametime client.

1.1. Changing Attributes through the Sametime System Console

The available attributes are:

  • Name
  • Company
  • E-mail
  • Telephone
  • Location
  • Title
  • Photo

Since the Business Card information is obtained from the LDAP Directory to which the IBM Sametime Community Server is connected, we must map the attributes:

Attribute Name LDAP Attribute
Name cn
Title title
Location postalAddress
Telephone telephoneNumber
E-mail Address mail
Photo jpegPhoto
Company ou

You can change the Business Card through the Sametime System Console.

Follow these steps:

1) Access the Sametime System Console

2) In the navigation panel (on the left), click on Sametime System Console

3) Expand Sametime Servers and click on Sametime Community Servers.

4) Click on the Deployment Plan of the Sametime Community Server.

5) Click on the Business Card tab.

6) Change the attributes, click OK to save the settings.

Restart the Sametime Community Server.

Figure 2: Business Card Configuration in the Sametime System Console

Despite the ease of using the Sametime Administration Console, we are limited to the available fields. Moreover, not all user information is stored in a single repository, such as an LDAP directory, due to performance reasons. For example, user photos.

1.2. The Business Card Subsystem

The Business Card subsystem of IBM Sametime retrieves information from the repositories configured in the UserInfoConfig.xml file.

These repositories can be:

  • An LDAP directory
  • A Notes application
  • A Java class, which in turn retrieves information from a SQL database or an ERP/SAP system.

The interface (API) that accesses these repositories is called the BlackBox.

The process of retrieving information by the Client from the repository is described below:

  1. The Sametime Client makes an HTTP (GET) request to a Sametime Community server.
  2. When the request reaches the Sametime/Domino HTTP server, Domino redirects the request to the UserInfoServlet servlet.
  3. The UserInfoServlet servlet reads the UserInfoConfig.xml file, which contains the connection information for the repositories.
  4. The servlet queries each repository to retrieve the information.
  5. The data from the repositories is returned to the UserInfo servlet.
  6. The servlet combines the responses from these repositories and converts them into an XML document.
  7. The HTTP server sends the XML document to the client, which extracts the data and displays it on the client.

Figure 3: Business Card Configuration in the Sametime System Console

1.3. Adicionando atributos através do UserInfoConfig.xml

O arquivo UserInfoConfig.xml permite uma maior flexibilidade na customização dos dados apresentados no Cartão de Visita.

O arquivo é gerado durante a instalação do Servidor Sametime Community e fica localizado no seguinte diretório (conforme a plataforma):

MS Windows:

<DOMINO_INSTALL_DIR>\UserInfoConfig.xml. 

Exemplo: C:\IBM\Domino\UserInfoConfig.xml.

Linux/AIX:

<DOMINO_DATA>\UserInfoConfig.xml

Exemplo: /local/notesdata

Ao abrirmos o arquivo UserInfoConfig.xml, você poderá observar, basicamente, duas seções:

Na seção <Storage type="LDAP">, temos as informações de conexão ao servidor LDAP

<Storage type="LDAP"> 
<StorageDetails
    HostName="ldapserver_hostname" Port="636" 
    UserName="" Password="" SslEnabled="false" SslPort="636" 
    BaseDN="" Scope="2" 
    SearchFilter="(&amp; (objectclass=organizationalPerson)(|(cn=%s)(givenname=%s)(sn=%s)(mail=%s)))" /> 
<!-- Add another StorageDetails tag to support another ldap server. The listing order implies the searching order --> 
<!-- Scope: 0=OBJECT_SCOPE 1=ONELEVEL_SCOPE 2=SUBTREE_SCOPE--> 

Listagem 1: Seção com as informações de conexão ao LDAP

Enquanto na seção Details, temos o mapeamento entre os Atributos do Sametime e do LDAP

    <Details> 
      <Detail Id="MailAddress" FieldName="mail" Type="text/plain"/> 
      <Detail Id="Name" FieldName="cn" Type="text/plain"/> 
      <Detail Id="Title" FieldName="title" Type="text/plain"/> 
      <Detail Id="Location" FieldName="postalAddress" Type="text/plain"/> 
      <Detail Id="Telephone" FieldName="telephoneNumber" Type="text/plain"/> 
      <Detail Id="Company" FieldName="ou" Type="text/plain" /> 
      <Detail Id="Photo" FieldName="jpegPhoto" Type="image/jpeg" /> 
    </Details> 
  </Storage> 
</Resources> 
<ParamsSets> 
  <Set SetId="0" params="MailAddress,Name,Title,Location,Telephone,Photo,Company"/> 
  <Set SetId="1" params="MailAddress,Name,Title,Location,Telephone,Photo,Company"/> 
</ParamsSets> 

Listagem 2: Seção com o mapeamento dos atributos

Vamos começar então o procedimento para adicionar novos campos:

Procedimento:

Antes de iniciarmos devemos por precaução realizar um backup do arquivo UserInfoConfig.xml

1) Edite o arquivo UserInfoConfig.xml

2) Localize a seção Details

3) Localize a entrada Telephone e vamos incluir o número do Celular.

<Detail Id="Telephone" FieldName="telephoneNumber,mobile" Type="text/plain" DisplaySeparator=" / " /> 

4) Antes da tag </Details>, vamos adicionar agora dois novos campos, como abaixo:

<Detail Id="State" FieldName="stateOrProvince" Type="text/plain"/>
<Detail Id="City" FieldName="city" Type="text/plain"/>

5) Localize a seção ParamsSets e adicione os novos campos

<ParamsSets> 
  <Set SetId="0" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State"/> 
  <Set SetId="1" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State"/> 
</ParamsSets> 

6) Salve e Feche o arquivo.

O arquivo final fica da seguinte maneira:

  <Details> 
     <Detail Id="MailAddress" FieldName="mail" Type="text/plain"/> 
     <Detail Id="Name" FieldName="cn" Type="text/plain"/> 
     <Detail Id="Title" FieldName="title" Type="text/plain"cod/> 
     <Detail Id="Location" FieldName="postalAddress" Type="text/plain"/> 
     <Detail Id="Telephone" FieldName="telephoneNumber,mobile" Type="text/plain" DisplaySeparator=" / " /> 
     <Detail Id="Company" FieldName="ou" Type="text/plain" /> 
     <Detail Id="Photo" FieldName="jpegPhoto" Type="image/jpeg" /> 
     <Detail Id="State" FieldName="stateOrProvince" Type="text/plain"/> 
     <Detail Id="City" FieldName="city" Type="text/plain"/>
    </Details> 
  </Storage> 
</Resources> 
<ParamsSets> 
  <Set SetId="0" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State"/> 
  <Set SetId="1" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State"/> 
</ParamsSets> 

Listagem 3: Resultado das alterações sobre o arquivo UserInfoConfig.xml

7) Reinicie o servidor Sametime Community

Para testar o resultado da alteração do UserInfoConfig.xml, você pode verificar o resultado retornado pelo servlet UserInfoServlet.

Em um navegador, entre com o endereço

http://<Sametime_Server>/servlet/UserInfoServlet?operation=3&setid=2&userid=<Test_Account_Name>

onde:

Parâmetro Descrição
operation Operação a ser executada. Utilize o valor 3.
setid Conjunto de parâmetros que devem ser retornados, definidos na seção ParamsSets do arquivo UserInfoConfig.xml
userid Chave de pesquisa

Exemplo:

 http://stserver/servlet/UserInfoServlet?operation=3&setid=2&userid=uid=ebasso

Onde o resultado

<?xml version="1.0" encoding="UTF-8"?>
<userinfo>
  <user id ="uid=ebasso">
   <field name="MailAddress" type="" error="UNAVAILABLE"/>
   <field name="Name" type="text/plain">Enio Rubens Basso</field>
   <field name="Title" type="text/plain">Especialista de TI</field>
   <field name="Location" type="" error="UNAVAILABLE"/>
   <field name="Telephone" type="text/plain">61-3333-4444 / 61-9999-9999</field>
   <field name="City" type="text/plain">Brasilia</field>
   <field name="State" type="text/plain">DF</field>
  </user>
</userinfo>

Listagem 4: Retorno do servlet

Como você pode ver, caso o valor de uma atributo no LDAP não esteja populado, o UserInfoServlet retorna error="UNAVAILABLE".

Adicionar campos provenientes do Sistema de RH da Empresa

Para atender o segundo desafio do departamento de Marketing, o Administrador do Sametime, precisa buscar as informações que se encontram no Sistema de RH da Empresa.

Para evitar realizar consultas a todo momento no Sistema de RH, vamos criar um repositório local para armazenar as informações a serem apresentadas no Cartão de Visita do Sametime.

Para realizar esta tarefa precisamos realizar 3 atividades:

  • Criar o repositório local
  • Importar os dados do Sistema de RH
  • Configurar o UserInfoConfig.xml.

Como pré requisito da tarefa, você vai precisar ter um Domino Designer instalado no seu computador, e configurado para acessar o servidor do Sametime Comunity. Utilize o usuario Administrador do Sametime para que nao tenha restricoes na criacao da database e de execucao no servidor.

2.1. Criando o repositório local

Vamos criar uma aplicacao Notes (NSF) para armazenar os dados.

1) Abra o Domino Designer

2) Crie a nova base, atraves do menu File -> Application -> New

Informe os seguintes campos

Campo Valor
Server <Nome do Servidor do Sametime>
Title Secondary Book Store
File name secbookstore.nsf
Server Local
Template Selecione -Blank-

Clique em OK

Figura 4: Caixa de Dialogo para criar uma nova aplicação

Vamos criar agora o formulário

4) Crie o novo formulario, atraves do menu Create -> Design -> Form

Campo Valor
Name person
Alias person
Comment
Application Secondary Book Store:\\<Nome do Servidor do Sametime>

Clique em OK

5) Crie o campo chave, denominado uid. Atraves do menu Create -> Design -> Field.

Informe no campo Name, o valor uid , defina como tipo Text.

Figura 5: Caixa de Dialogo para criar uma novo campo

6) Vamos criar os demais campos usados neste artigo.

Nome do Campo Tipo Descrição
dpto Text Departamento
updated Text Data de atualização da foto
PhotoURL Text URL da Imagem
Photo Rich Text Lit arquivo da imagem

Salve o formulario, atraves do menu File -> Save.

Figura 6: Novos campos criados

Vamos criar a visao de indice

7) Crie uma nova visao, atraves do menu Create -> Design -> View

Informe:

Campo Valor
View Name vwIndex
View Type Shared
Select Conditions By Formula
Select Conditions Select @All

Clique em Save and Customize

Figura 6: Caixa de Dialogo para criar visão

8) Clique na coluna #, selecione Field e selecione uid.

Figura 7: Definindo o valor da coluna

9) Na caixa de diálogo de propriedades, clique na segunda aba e em sort clique em Ascending.

Figura 8: Definindo o tipo de ordenacao

Salve a visao, atraves do menu File -> Save.

Agora ja possuímos os uma repositório secundário local.

2.2. Importando os dados do Sistema de RH

O Sistema de RH da empresa fica armazenado em um banco de Dados DB2.

Nesta seção o vamos criar um agente na linguagem Java para buscar as informacoes da base de dados SQL , e popular o repositorio NSF local.

O nosso agente esta divido em 5 partes:

  1. Definição das variáveis
  2. Inicialização do Driver JDBC do DB2
  3. Execução da query
  4. Criação ou Atualização do documento no repositório NSF
  5. Método principal

Preparação:

Como preparação para o acesso ao DB2, devemos adicionar os drivers JDBC (tipo 4) do DB2.

Dentro do diretorio <DOMINO_INSTALL_DIR>\ibm-jre\jre\lib\ext, devemos copiar os arquivos:

  • db2jcc.jar
  • db2jcc_license_cu.jar

Figura 9: Configuracao dos drivers JDBC do DB2

Procedimento:

Crie o novo atraves do menu Create -> Design -> Agent

Campo Valor
Name ImportPersonInfo
Alias ImportPersonInfo
Comment
Type Java
Application Secondary Book Store:\\<Nome do Servidor do Sametime>

Clique em OK

2) Em Basics, defina On Schedule -> Daily, em Target defina None.

3) Em Security, defina 3. Allow restricted operations with full administration rights.

4) Click em JavaAgent.java para criarmos o código.

5) Dentro da Classe JavaAgent, devemos definir as contantes de conexao ao DB2, variaveis globais a classe, ...

// CONSTANTES
private static final String JDBC_CLASS = "com.ibm.db2.jcc.DB2Driver"; 
private static final String JDBC_URL = "jdbc:db2://db2srv.empresax.com.br:50000/RHS"; 
private static final String JDBC_USERID = "STUSER"; 
private static final String JDBC_PASSWORD = "STUSER"; 
private static final String UID_LOOKUP_VIEW_NAME = "vwIndex"; 
private static final String SQL = 
"SELECT UID, DPTO " + 
"FROM EMPLOYEE " + 
"ORDER BY UID"; 

// VARIAVEIS GLOBAIS A CLASSE
Connection con; 
String uid = ""; 
String dpto = "";

6) Inicializacao do Driver JDBC do DB2

private void initDB() throws Exception { 
 // Load the requested JDBC driver type 
 Class.forName(JDBC_CLASS).newInstance(); 

con = DriverManager.getConnection(JDBC_URL, JDBC_USERID, JDBC_PASSWORD); 
}

7) Execucao da query

Para cada linha retornada pelo SELECT, vamos chamar o metodo updateOrCreateDocument.

private void runMain(Database db) throws Exception { 

 Statement stmt = con.createStatement(); 
 System.out.println("runQuery - start"); 
 ResultSet rs = stmt.executeQuery(SQL); 
 System.out.println("runQuery - end"); 
 int i=0; 

 System.out.println("Iterating: " + i); 

 while (rs.next()) { 
   if (++i % 1000 == 0) { 
     System.out.println("Iterating: " + i); 
   } 
   uid = rs.getString("UID"); 
   if (uid == null) uid = ""; 
   dpto = rs.getString("DPTO"); 
   if (dpto == null) dpto = ""; 
   updateOrCreateDocument(db,uid); 
 } 
 stmt.close(); 
 System.out.println("Total: " + i); 
}

8) Criação ou Atualização do documento no repositorio NSF

Com a chave primária, armazenada na string key, verificamos a existencia ou nao do documento. Se o resultado for vazio, criamos um novo documento senao verificamos por mudancas e entao atualizamos o documento.

private void updateOrCreateDocument(Database db, String key) throws Exception { 
 View view = db.getView(UID_LOOKUP_VIEW_NAME); 
 Document doc = null; 
 boolean saveDoc = false; 
 doc = view.getDocumentByKey(key, true); 
 if (doc == null){ 
   doc = db.createDocument(); 
   doc.replaceItemValue("Form","person"); 
   doc.replaceItemValue("uid", uid); 
   doc.replaceItemValue("dpto", dpto); 
   saveDoc = true; 
 } else { 
  if (!uid.equals("") && !uid.equals(doc.getItemValueString("uid"))){ 
     doc.replaceItemValue("uid", uid); 
     saveDoc = true; 
   } 
   if (!dpto.equals("") && !dpto.equals(doc.getItemValueString("dpto"))){ 
     doc.replaceItemValue("dpto", dpto); 
     saveDoc = true; 
   } 
 } 
 if (saveDoc) { 
   doc.save(true, false, true);    
 } 
 doc.recycle(); 
 view.recycle(); 
}

9) No metodo principal NotesMain, chamamos os demais metodos.

public void NotesMain() { 
 try { 
   Session session = getSession(); 
   AgentContext agentContext = session.getAgentContext(); 

   // (Your code goes here) 
   Database notedDb = agentContext.getCurrentDatabase(); 
   System.out.println("ImportPersonInfo - start"); 
   initDB(); 
   runMain(notedDb); 
   System.out.println("ImportPersonInfo - end"); 
 } catch(Exception e) { 
   e.printStackTrace(); 
 } 
}

2.3. Configurando o UserInfoConfig.xml para utilizar o repositorio local

Como um pre-requisito para a desta secao eh termos uma chave primaria entre o primeiro repositorio LDAP e o segundo repositorio NSF. Neste caso o valor do campo uid sera populado com os mesmos valores.

1) Edite o arquivo UserInfoConfig.xml

2) Localize a tag </Storage>, e adicione o novo repositorio:

<Storage type="NOTES_CUSTOM_DB"> 
<StorageDetails DbName="secbookstore.nsf" View="vwIndex"/> 
<Details> 
<Detail Id="Dpto" FieldName="Dpto" Type="text/plain"/> 
<Detail Id="PhotoURL" FieldName="PhotoURL" Type="text/plain"/> 
<Detail Id="Photo" FieldName="photo" Type="image/jpeg" /> 
</Details> 
</Storage>

3) Localize a seção <ParamsSets> e adicione os novos campos

<ParamsSets> 
  <Set SetId="0" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State,Dpto"/> 
  <Set SetId="1" params="MailAddress,Name,Title,Location,Telephone,Photo,Company,City,State,Dpto"/> 
</ParamsSets> 

4) Localize a seção <BlackBoxConfiguration> e adicione os novos blackbox

<BlackBox type="NOTES_CUSTOM_DB" name="com.ibm.sametime.userinfo.userinfobb.UserInfoNotesCustomBB" MaxInstances="4"/>

5) Salve e Feche o arquivo.

6) Reinicie o servidor Sametime Community

3. Apresentar a foto do usuário armazenada no Perfil do IBM Connections

Por fim iremos utilizar as fotos armazenadas nos Perfis do IBM Connections para serem apresentadas nos IBM Sametime.

No IBM Connections, as fotos do Perfis ficam armazenados no banco de dados, dentro da tabela EMPINST.PHOTO. O acesso direto às tabelas do Perfis não é suportado pela IBM, mas iremos utilizar aqui neste artigo.

Aqui vamos adicionar adicionar 2 campos princípais:

  • Photo: Campo RichText utilizado para armazenar o binario da foto utilizada pelo Sametime Connect Client
  • PhotoURL: Url da foto utilizado pelo Sametime Web Client (Sametime Proxy)

Para evitar a comparação de 2 arquivos, criamos o campo updated, a qual possui a data de alteração do arquivo de foto.

3.1. Importando as fotos do IBM Connections

O nosso agente está divido em 6 partes:

1) Definição das variáveis

2) Inicialização do Driver JDBC do DB2

3) Execucao da query

4) Criar o arquivo de Imagem

5) Criação ou Atualização do documento no repositório NSF

6) Método principal

Por se tratar da mesma abordagem usada na seção anterior, vamos apresentar apenas as diferenças

Procedimento:

1) Crie o novo através do menu Create -> Design -> Agent

Campo Valor
Name ImportaFotosConnections
Alias ImportaFotosConnections
Comment
Type Java
Application Secondary Book Store:\\<Nome do Servidor do Sametime>

Clique em OK

Repita os passos 2, 3, 4 do item 2.2.

5) Dentro da Classe JavaAgent, vamos adicionar novas contantes de conexao ao DB2, variaveis globais a classe, ...

private static final String PHOTOS_TEMP_DIRECTORY = "c:\\temp\\fotos\\img_"; 
private static final String PHOTO_URL_PREFIX = "http://connections.empresax.com.br/profiles/photo.do?uid="; 
private static final String SQL = 
        "SELECT E.PROF_UID UID, P.PROF_UPDATED UPDATED, P.PROF_IMAGE IMAGE " + 
        "FROM EMPINST.PHOTO P, " + 
        "EMPINST.EMPLOYEE E " + 
        "WHERE P.PROF_KEY=E.PROF_KEY"; 

String updated = ""; 
byte[] photo_bytes ; 

A variável PHOTOS_TEMP_DIRECTORY armazena o diretorio temporario para armazenar as fotos.

A variável PHOTO_URL_PREFIX armazena a url para busca das fotos no IBM Connections.

Repita os passos 6 do item 2.2.

7) Execucao da query

Para cada linha retornada pelo SELECT, eh necessario criar um arquivo com a foto do usuario em um diretorio temporario, atraves do metodo createImageFile, logo depois devemos chamar o metodo updateOrCreateDocument.

private String createImageFile(String uid) throws Exception { 

 String filename = PHOTOS_TEMP_DIRECTORY + uid + ".jpg"; 
 File outFile = new File(filename); 
 FileOutputStream fos = new FileOutputStream(outFile); 
 fos.write(photo_bytes); 
 fos.close(); 
 return filename; 
} 

private void runMain(Database db) throws Exception { 
 Statement stmt = con.createStatement(); 
 System.out.println("runQuery - start"); 
 ResultSet rs = stmt.executeQuery(SQL); 
 System.out.println("runQuery - end"); 
 int i=0; 
 System.out.println("Iterating: " + i); 
 while (rs.next()) { 
   if (++i % 1000 == 0) { 
     System.out.println("Iterating: " + i); 
   } 
   uid = rs.getString("UID"); 
   if (uid == null) uid = ""; 
   updated = rs.getString("UPDATED"); 
   photo_bytes = rs.getBytes("IMAGE"); 
   String filename = createImageFile(uid); 
   updateOrCreateDocument(db,uid,filename);
 } 
 stmt.close(); 
 System.out.println("Total: " + i); 
}


8) Criacao ou Atualizacao do documento no repositorio NSF

Com a chave primaria, armazenada na string key, verificamos a existencia ou nao do documento. Se o resultado for vazio, criamos um novo documento senao verificamos por mudancas e entao atualizamos o documento.

private void updateOrCreateDocument(Database db, String key) throws Exception { 

 View view = db.getView(UID_LOOKUP_VIEW_NAME); 
 Document doc = null; 
 boolean saveDoc = false; 

 doc = view.getDocumentByKey(key, true); 

 if (doc == null){ 
   doc = db.createDocument(); 
   doc.replaceItemValue("Form","person"); 
   doc.replaceItemValue("uid", uid); 
   doc.replaceItemValue("updated", updated); 
   doc.replaceItemValue("PhotoURL", PHOTO_URL_PREFIX + uid); 
   photo = doc.createRichTextItem("photo"); 
   photo.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null, filename, null); 
   saveDoc = true; 
 } else { 
   if (!uid.equals("") && !uid.equals(doc.getItemValueString("uid"))){ 
     doc.replaceItemValue("uid", uid); 
     saveDoc = true; 
   } 
    if (!updated.equals("") && !updated.equals(doc.getItemValueString("updated"))){ 
     doc.replaceItemValue("updated", updated); 
     doc.removeItem("photo"); 
     doc.replaceItemValue("PhotoURL", PHOTO_URL_PREFIX + uid); 
     photo = doc.createRichTextItem("photo"); 
     photo.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null, filename, null); 
    saveDoc = true; 
   } 
 } 
 if (saveDoc) { 
   doc.save(true, false, true);    
 } 
 doc.recycle(); 
 view.recycle(); 

}

9) No metodo principal NotesMain, chamamos os demais metódos.

3.2. Configurando o UserInfoConfig.xml para retornar as fotos

1) Edite o arquivo UserInfoConfig.xml

2) Localize a secao <Storage>, e adicione o novos campos:

<Storage type="NOTES_CUSTOM_DB"> 
<StorageDetails DbName="secbookstore.nsf" View="vwIndex"/> 
<Details> 
  <Detail Id="Dpto" FieldName="Dpto" Type="text/plain"/> 
  <Detail Id="PhotoURL" FieldName="PhotoURL" Type="text/plain"/> 
  <Detail Id="Photo" FieldName="photo" Type="image/jpeg" /> 
  </Details> 
</Storage>

3) Salve e Feche o arquivo.

4) Reinicie o servidor Sametime Community

Conclusão

Este artigo descreveu como extender o IBM Sametime para prover informações aos usuários armazenadas em diversos repositórios. Mostramos como criar um repositório próprio buscando informações de outras fontes como um base SQL. E importando as fotos dos perfis do IBM Connections.

Caso voce tenha um Cluster de IBM Sametime Community Server, basta criar uma replica da base secbookstore.nsf e copiar o arquivo UserInfoConfig.xml para os demais servidores.

Espero que o artigo seja útil no seu dia como Administrador Sametime.

Recursos

Ver também