segunda-feira, 14 de maio de 2012

Zipar um arquivo no Notes

No exemplo abaixo, foi criado um agente chamando uma  biblioteca de scripts java:

AGENTE:
######################################################################
(Options)

Uselsx "*javacon" 'Which lets you use Java from LotusScript
Use "ZipFile" 'A Java library that holds a function to do zipping



Sub Zip()
Dim js As JAVASESSION
Dim zipClass As JAVACLASS
Dim zipFileObject As JavaObject
Dim strOutFilePath As String, strReturnCode As String

Set js = New JAVASESSION
Set zipClass = js.GetClass("ZipFile")
Set zipFileObject = zipClass.CreateObject
strOutFilePath = Strleft(StrArquivo, ".") + ".zip"

strReturnCode = zipFileObject.zipMyFile(StrArquivo, strOutFilePath, 1) 'Calling the zip function

Kill StrArquivo
StrArquivo = strOutFilePath

If Not strReturnCode = "OK" Then Error 1010, "An Error occurred"

End Sub
######################################################################


Código da biblioteca de scripts:
######################################################################

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {
 public String zipMyFile(String fileToZip, String zipFilePath, int intType) {
  String result = "";

      byte[] buffer = new byte[18024];

      // Specify zip file name
      String zipFileName = zipFilePath;
   
      try {

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));

        // Set the compression ratio
out.setLevel(Deflater.BEST_COMPRESSION);

          System.out.println(fileToZip);
          // Associate a file input stream for the current file
FileInputStream in = new FileInputStream(fileToZip);

if (intType == 1)
{
fileToZip  = fileToZip.substring(fileToZip.lastIndexOf("\\"), fileToZip.length());
}

          // Add ZIP entry to output stream.
          out.putNextEntry(new ZipEntry(fileToZip));

          // Transfer bytes from the current file to the ZIP file
          //out.write(buffer, 0, in.read(buffer));

          int len;
         while ((len = in.read(buffer)) > 0)
         {
         out.write(buffer, 0, len);
        }

          // Close the current entry
          out.closeEntry();

          // Close the current file input stream
          in.close();

        // Close the ZipOutPutStream
        out.close();
      }
      catch (IllegalArgumentException iae) {
        iae.printStackTrace();
   return "ERROR_ILLEGALARGUMENTSEXCEPTION";
      }
      catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    return "ERROR_FILENOTFOUND";
      }
      catch (IOException ioe)
      {
      ioe.printStackTrace();
      return "ERROR_IOEXCEPTION";
      }


  return "OK";

  }
}

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




quarta-feira, 18 de abril de 2012

Lotus Connector Data Access


USO DA FUNCIONALIDADE:


Use "Lotus Connector Data Access"
Dim objOracle As LotusConnectorDataAccess

aux  = |QUERY|


Set objOracle = New LotusConnectorDataAccess("oracle", "DatabaseName", usuario, senha)

If objOracle.Connect Then
If objOracle.ExecuteSQL(aux) Then
msgbox "QUERY EXECUTADA"
Exit Function

Else

Call objOracle.Disconnect
Exit Function

End If




SCRIPT LIBRARIES:

Option Public
Uselsx "*lsxlc"
Public Class LotusConnectorDataAccess
objConn As LCConnection

Private strLocalDBType As String
Private strLocalDatabase As String
Private strLocalUser As String
Private strLocalPassword As String
Private lngLocalRowsReturned As Long
Private flLocalFieldList As LCFieldList

'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'OBJETIVO: Construtor da classe
'PARAMETROS: strDBType -> Tipo de banco de dados (oracle, db2, etc)
'            strDatabase -> Nome do banco de dados a ser acessado
'                                   strUser -> O nome do usuário a conectar no banco de dados. Se não precisar e só passar ""
'                          strPassword -> A senha do usuário a conectar no banco de dados. Se não precisar e só passar ""
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Public Sub New(strDBType As String, strDatabase As String, strUser As String, strPassword As String)
DBType = strDBType
DatabaseName = strDatabase
UserName = strUser
Password = strPassword

Set OracleConection = New LCConnection(strDBType)
End Sub

'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'OBJETIVO: Destrutor da classe
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Public Sub Delete
Set objConn = Nothing
End Sub

Public Property Get RowsReturned As Long
RowsReturned = lngLocalRowsReturned
End Property

Public Property Set RowsReturned As Long
lngLocalRowsReturned = RowsReturned
End Property

Public Property Get DBType As String
DBType = strLocalDBType
End Property

Public Property Set DBType As String
strLocalDBType = DBType
End Property

Public Property Get DatabaseName As String
DatabaseName = strLocalDatabase
End Property

Public Property Set DatabaseName As String
strLocalDatabase = DatabaseName
End Property

Property Get UserName As String
UserName = strLocalUser
End Property

Property Set UserName As String
strLocalUser = UserName
End Property

Property Get Password As String
Password = strLocalPassword
End Property

Property Set Password As String
strLocalPassword = Password
End Property

Public Property Get FieldListReturned As LCFieldList
Set FieldListReturned = flLocalFieldList
End Property

Public Property Set FieldListReturned As LCFieldList
Set flLocalFieldList = FieldListReturned
End Property

Public Property Get OracleConection As LCConnection
Set OracleConection = objConn
End Property

Public Property Set OracleConection As LCConnection
Set objConn = OracleConection
End Property

'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'OBJETIVO: Conecta no banco de dados
'RETORNO: TRUE -> Se a conexão foi realizada com sucesso
'                   FALSE -> Se a conexão não foi estabelecida
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Public Function Connect() As Integer
On Error Goto Error_Handler

Select Case DBType
Case "oracle":
objConn.Server = DatabaseName
objConn.Userid = Username
objConn.Password = Password
objConn.Connect
Connect = True

Case "db2":
objConn.Database = DatabaseName
objConn.Userid = Username
objConn.Password = Password
objConn.Connect
Connect = True

Case Else
Msgbox "A classe não implementa acesso ao banco da dados " + DBType, 0+16, "Atenção"
Connect = False
End Select

Goto Fim

Error_Handler:
Msgbox "Ocorreu um erro ao tentar conectar ao banco de dados." + Chr(13) + Chr(10) + _
"Número: " + Cstr(Err) + " - Descrição: " + Error, 0+16, "Erro"
Connect = False
Resume Fim

Fim:
End Function

Public Sub Disconnect
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'OBJETIVO: Desconecta do SQL
'PARAMETROS: Nenhum
'RETORNO: Nenhum
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If objConn.IsConnected Then
objConn.Disconnect
End If
End Sub

Public Function ExecuteSQL(strSQL As String) As Variant
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'OBJETIVO: Executa um comando SQL que pode ser SELECT, DELETE, UPDATE, INSERT
'PARAMETROS: strSQL -> A query que sera enviada ao banco de dados
'           fieldListReturned -> Retorna uma coleção de dados caso a query seja um select.
'RETORNO: TRUE -> Se a query foi executada com sucesso
'                   FALSE -> Se a query não foi executada com sucesso
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
On Error Goto Error_Handler

If objConn.IsConnected Then
Set FieldListReturned = New LCFieldList
RowsReturned = objConn.Execute(strSQL, FieldListReturned)
ExecuteSQL = True
Else
ExecuteSQL = False
End If
Goto Fim

Error_Handler:
Msgbox "Ocorreu um erro na função ExecuteSQL: " + Chr(13) + Chr(10) + _
"Número: " + Cstr(Err) + " - Descrição: " + Error, 0+16, "Erro"
ExecuteSQL = False
Resume Fim

Fim:
End Function
End Class

quarta-feira, 8 de fevereiro de 2012

Retorna a posição do maior valor dentro de um array

Ref: Notes/Domino 4 and 5 Forum


Function MaxIndex( inputArray As Variant ) As Integer
' ----------------------------------------------------------------------------------------------------------------------------------
' MaxIndex( ) written by Trent Overton - toverton@wgcinc.com
' ----------------------------------------------------------------------------------------------------------------------------------
' Description
' Finds the maximum value in an array and returns the index to that element.
' Note: Array must contain values which can be compared with standard operators.

' Parameters
' inputArray - array passed as variant data type
'
' Return value
' integer representing index to largest element in array.
' error conditions cause return value to be -1
'
' ---------------------------------------------------------------------------------------------------------------------------------- 

On Error Goto ErrorHandler

Dim rc As Integer
rc = -1
If Isarray( inputArray ) Then
Dim index As Integer
For index = Lbound( inputArray ) To Ubound( inputArray )
If rc = -1 Then 
rc = index
Elseif inputArray( index ) > inputArray( rc ) Then
rc = index
End If
Next
End If

MaxIndex = rc

ErrorHandler:
rc = -1
Resume Next

End Function