quarta-feira, 2 de abril de 2014

Buscando informações no Names com ajax e json


1º Criar a bilbioteca de javascript de  Ajax

#############################################################################

function AJAX(url, metodo, params, processa, modo) {
 this.url = url;
 this.metodo = (metodo)? metodo : 'GET';
 this.params = (metodo='GET')? null : params;
 this.processaresultado = processa;
 this.modo = (modo) ? modo : 'T';
 if(this.modo!='T' && this.modo!='X'){
  this.modo='T';
 }
 this.conectar();
}

AJAX.prototype = {
conectar: function() {
  if(this.url==undefined || this.url==''){
   return;
  }
  this.httprequest = null;
  if (window.XMLHttpRequest){
  this.httprequest = new XMLHttpRequest();
  if(this.metodo=='POST')
   this.httprequest.setRequestHeader('Content-length', params.length );
  } else if (window.ActiveXObject) {
   try {
    this.httprequest = new ActiveXObject("Msxml2.XMLHTTP");
   } catch(e){
    try{
     this.httprequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {}
   }
  }
  if(this.httprequest!=null && this.httprequest!=undefined) {
   var obj = this;
   this.httprequest.onreadystatechange = function() {
    obj.processaretorno.call(obj);
   }
   this.httprequest.open(this.metodo,this.url,true);
   this.httprequest.send(this.params);
  }
 },
processaretorno : function(){
  if(this.httprequest.readyState==4){
   if(this.httprequest.status==200) {
    var resp = (this.modo=='T')? this.httprequest.responseText : this.httprequest.responseXML;
    if(this.processaresultado!=null){
     this.processaresultado(resp);
    } else {
     document.write(resp);
    }
   } else {
    this.processaerro();
   }
  }
 },
processaerro: function() {
  alert(this.httprequest.status + ' - ' + this.httprequest.statusText + ' :-> ' + this.url);
 }
}
function getHash() {
 return new Date().getTime();
}
##############################################################################

2º  Criar função que executara a chamada do agente lotusscript/java para realizar a consulta e criar o objeto Json


##############################################################################


//Busca dados por Chave
function buscaDadosPorChave(chave,t_funcao){
// S => solicitante
// B => beneficiario

if(chave == null) return;

if(chave.length != 4){
alert("A chave " + chave + " é inválida. A chave deverá conter 4 dígitos.");
return false;
}else{
var tdoc = new TDocument();
var ajax = new AJAX();
vurl = "http://"+ tdoc.server+ "/" + tdoc.pathname +"/ag_BuscaDadosporChaveWeb?OpenAgent&chave="+chave+"&hash="+getHash();
ajax.url = vurl;
ajax.modo = 'T';
ajax.metodo ="GET"
ajax.processaresultado = t_funcao
ajax.conectar();
}
}
//Fim da Busca por Chavee

##############################################################################

3º criação do agente p/buscar as informações no Names/base de informações de usuário


Sub Initialize
On Error GoTo error_handler

Dim m_Session As New NotesSession
Dim m_docContext As NotesDocument

Set m_docContext = m_Session.DocumentContext

Dim t_strChave As String
t_strChave = f_retornaParametroURL (m_docContext.Query_String(0),"chave")

Dim m_docPerson As NotesDocument
Set m_docPerson = getDocPersonNames(t_strChave)


'cria o objeto json
Print "Content-type: text/html;charset=utf-8"
Print "{"

If m_docPerson Is Nothing Then
Print |"localizado":"0",|
Print |"chave":"não encontrado",|
Print |"nomenotes":"não encontrado",|
Print |"orgao":"não encontrado",|
Print |"ramal":"não encontrado",|
Print |"matricula":"não encontrado",|
Print |"identificacao":"não encontrado",|
Print |"situacaocontratual":"não encontrado",|
Print |"funcao" :"não encontrado"|
Else
Dim t_name As NotesName
Set t_name = New NotesName(m_docPerson.ca_nomeNotes(0))

Set nome = New NotesName(m_docPerson.FullName(0))
Print |"localizado":"1",|
Print |"chave":"|+ EscapeJS(m_docPerson.ca_chave(0)) +|",|
Print |"nomenotes":"|+ EscapeJS(t_name.Abbreviated) +|",|
Print |"orgao":"|+ EscapeJS(m_docPerson.ca_orgaoMenor(0))+|",|
Print |"ramal":"| + EscapeJS(m_docPerson.ca_ramalSITEL(0))+|",|
Print |"matricula":"| + EscapeJS(m_docPerson.ca_matricula(0))+|",|
Print |"identificacao":"| + EscapeJS(m_docPerson.ca_identificacao(0))+|",|
Print |"situacaocontratual":"| + EscapeJS(retornaVinculo(m_docPerson.ca_vinculo(0)))+|",|
Print |"regiao":"|+ EscapeJS(m_docPerson.ca_regiao(0))+|",|
Print |"funcao":"| + EscapeJS(m_docPerson.ca_funcao(0))+|"|

End If

Print "}"

Exit Sub

Error_Handler:
'Print||
Print {}
Call LogError()
Exit sub
End Sub

Function f_retornaParametroURL(ByVal t_qry As String,ByVal t_param As String ) As String
On Error GoTo trataerro

Dim i,j As Integer
Dim result As String
i = InStr(1, t_qry, t_param)
result= ""
If i > 0 Then
j = InStr(i, t_qry, "&")
If j > 0 Then
result$ = Mid(t_qry, i + Len(t_param) + 1, (j - 1) - (i + Len(t_param)))
Else
result$ = Mid(t_qry, i + Len(t_param) + 1)
End If
End If
f_retornaParametroURL = result

trataerro:
Call AddToStackTrace()
End Function




Function EscapeJS(ByVal a_strOrigem As String) As String
On Error GoTo ErrorHandler
Dim t_astrBusca(0 To 1) As String
t_astrBusca(0) = |\|
t_astrBusca(1) = |"|
Dim t_astrSubst(0 To 1) As String
t_astrSubst(0) = |\\|
t_astrSubst(1) = |\"|

Dim t_astrSource(0 To 0) As String
t_astrSource(0) = a_strOrigem

Dim t_astrRet As Variant
t_astrRet = Replace(t_astrSource, t_astrBusca, t_astrSubst)

EscapeJS = t_astrRet(0)

Exit Function
ErrorHandler:
Call AddToStackTrace()
End Function



##############################################################################

4 º Função para popular o documento web.

function atualizaCamposSolicitante(txt){

var obj = eval ("(" + txt + ")");

if (obj.localizado == '0') {
alert('Chave não encontrada na base de pessoal.\nFavor informar a chave correta.');
document.getElementById("ca_PEDSolicitanteLocalizado").value = "0";
}else{
document.getElementById("ca_PEDSolicitanteLocalizado").value = "1";
}

document.getElementById("PEDsolicitanteTX").value = obj.nomenotes;
document.getElementById("PEDsolicitantelotacaoTX").value = obj.orgao;
document.getElementById("PEDsolicitanteramalTX").value = obj.ramal;
document.getElementById("PEDfuncaoTX").value = obj.funcao;


}

function atualizaCamposBeneficiario(txt){

var obj = eval ("(" + txt + ")");

if (obj.localizado == '0') {
alert('Chave não encontrada na base de pessoal.\nFavor informar a chave correta.');
document.getElementById("ca_PEDbeneficiarioLocalizado").value = "0";
}else{
document.getElementById("ca_PEDbeneficiarioLocalizado").value = "1";
}

document.getElementById("ca_PEDbeneficiarioNomeTX").value = obj.nomenotes;
document.getElementById("ca_PEDbeneficiarioNomeTX").value = obj.nomenotes;
document.getElementById("ca_PEDbeneficiarioUnidadeTX").value = obj.orgao;
document.getElementById("ca_PEDbeneficiarioCargoTX").value = obj.funcao;
document.getElementById("ca_PEDbeneficiarioRamalTX").value = obj.ramal;
document.getElementById("ca_PEDbeneficiarioRegiaoTX").value = obj.regiao;
document.getElementById("ca_PEDbeneficiarioMatriculaTX").value = obj.matricula;
document.getElementById("ca_PEDbeneficiarioIdentificadorTX").value = obj.identificacao;
document.getElementById("ca_PEDbeneficiarioSContratualTX").value = obj.situacaocontratual;

}


##############################################################################
5º Chamada da ação
'// do exemplo ficou no evento onBlur
'// informa a chave e a funcao desejada

buscaDadosPorChave(this.value,funcao)

##############################################################################

Java - Sending Email using JavaMail API

Ref: http://www.tutorialspoint.com/java/java_sending_email.htm


To send an e-mail using your Java Application is simple enough but to start with you should haveJavaMail API and Java Activation Framework (JAF) installed on your machine.
You can download latest version of JavaMail (Version 1.2) from Java's standard website.
You can download latest version of JAF (Version 1.1.1) from Java's standard website.
Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH.
Send a Simple E-mail:
Here is an example to send a simple e-mail from your machine. Here it is assumed that your localhostis connected to the internet and capable enough to send an email.
// File Name SendEmail.java

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

public class SendEmail
{
   public static void main(String [] args)
   {  
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
Compile and run this program to send a simple e-mail:
$ java SendEmail
Sent message successfully....
If you want to send an e-mail to multiple recipients then following methods would be used to specify multiple e-mail IDs:
void addRecipients(Message.RecipientType type,
                   Address[] addresses)
throws MessagingException
Here is the description of the parameters:
type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO
addresses: This is the array of email ID. You would need to use InternetAddress() method while specifying email IDs
Send an HTML E-mail:
Here is an example to send an HTML email from your machine. Here it is assumed that your localhostis connected to the internet and capable enough to send an email.
This example is very similar to previous one, except here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message.
Using this example, you can send as big as HTML content you like.
// File Name SendHTMLEmail.java

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

public class SendHTMLEmail
{
   public static void main(String [] args)
   {
   
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Send the actual HTML message, as big as you like
         message.setContent("

This is actual message

",
                            "text/html" );

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
Compile and run this program to send an HTML e-mail:
$ java SendHTMLEmail
Sent message successfully....
Send Attachment in E-mail:
Here is an example to send an email with attachment from your machine. Here it is assumed that yourlocalhost is connected to the internet and capable enough to send an email.
// File Name SendFileEmail.java

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

public class SendFileEmail
{
   public static void main(String [] args)
   {
   
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Create the message part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText("This is message body");
       
         // Create a multipar message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         message.setContent(multipart );

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
Compile and run this program to send an HTML e-mail:
$ java SendFileEmail
Sent message successfully....
User Authentication Part:
If it is required to provide user ID and Password to the e-mail server for authentication purpose then you can set these properties as follows:
 props.setProperty("mail.user", "myuser");
 props.setProperty("mail.password", "mypwd");
Rest of the e-mail sending mechanism would remain as explained above.