Mostrando postagens com marcador Java. Mostrar todas as postagens
Mostrando postagens com marcador Java. Mostrar todas as postagens
segunda-feira, 2 de junho de 2014
Descompactar arquivos zip em Lotus Script utilizando LS2J
Como Lotus Script não possui uma classe nativa para compactar () ou descompactar arquivos no formato '.zip', Criei essa funcionalidade utilizando 'ls2j' para conectar na classe java.
Necessidade: Extrair o arquivo compactado do campo richtext e exibir o arquivo 'Player.html'.
1º Criação de um agent Lotus Script com o código abaixo:
Option Public
Option Declare
UseLSX "*javacon"
Use "bib_unZip"
Sub Initialize
On Error GoTo trataerro
Dim ses_Sessao As New NotesSession
Dim ws_AreaTrabalho As New NotesUIWorkspace
Dim rti_anexos As NotesRichTextItem
Dim doc_Anexo As NotesDocument
Dim strCaminho As String
Dim strNomeAnexoZip As String
Set doc_Anexo = ws_AreaTrabalho.Currentdocument.Document
Set rti_anexos = doc_Anexo.Getfirstitem("ca_AnexoConvertido")
If Not rti_anexos Is Nothing Then
If ( rti_anexos.Type = RICHTEXT ) Then
If Not IsEmpty( rti_anexos.EmbeddedObjects ) Then
strCaminho = Environ("temp")
strCaminho = MkDir(strCaminho + "\" + doc_Anexo.Universalid)
ForAll Anexo In rti_Anexos.EmbeddedObjects
If Anexo.Type = EMBED_ATTACHMENT Then
Call Anexo.ExtractFile(strCaminho & Anexo.Source)
strNomeAnexoZip = Anexo.Source
End If
End ForAll
Else
MsgBox |Documento não possui anexo convertido!|,64,|Operação Cancelada|
Exit Sub
End If
End If
End If
Dim strFullPathZip As String
strFullPathZip = strCaminho & strNomeAnexoZip
If strNomeAnexoZip = "" Then
MsgBox |Documento não possui anexo convertido!|,64,|Operação Cancelada|
Kill strFullPathZip
Exit sub
End If
Dim strExtensaoAnexo As String
strExtensaoAnexo = |.|&LCase(StrRightBack(CStr(strNomeAnexoZip), "."))
If (strExtensaoAnexo <> ".zip" )Then
MsgBox |Arquivo convertido contem arquivos inválidos!|,64,|Operação Cancelada|
Kill strFullPathZip
Exit Sub
End If
Dim mySession As JavaSession
Dim zipClass As JavaClass
Dim zipFileObject As JavaObject
Set mySession = New JavaSession()
Set zipClass = mySession.GetClass("br.com.unzip.controller.UnZip")
Set zipFileObject = zipClass.CreateObject()
Call zipFileObject.ziparArquivo(strFullPathZip)
Dim returnZipExtractFolder As String
returnZipExtractFolder = zipFileObject.getDestinationFolder()
If Trim(returnZipExtractFolder)="" Then
Error 1001,|Não foi possível descompactar o arquivo : | & strFullPathZip
Exit Sub
End If
Dim intRespostaShell As Integer
intRespostaShell = Shell("explorer " & returnZipExtractFolder & "\Player.html",1)
Exit Sub
trataerro:
MsgBox "Aconteceu um erro inesperado, favor, contactar o administrador!",16,"Operação Cancelada!"
Call logError()
Exit sub
End Sub
2º Criação da biblioteca de script 'bib_UnZip' em Java com os métodos p/compactar.
Classe Progresso. => Progressive dialog
package br.com.unzip.view;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.ProgressMonitor;
public class Progresso {
ProgressMonitor progress;
public Progresso(String strMensagem, String strAlerta, int intMaximo){
JFrame frame = new JFrame();
WindowListener exitListener;
exitListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = e.getWindow();
window.setVisible(false);
window.dispose();
System.exit(0);
}
};
frame.addWindowListener(exitListener);
progress = new ProgressMonitor(frame, strMensagem, strAlerta, 0, intMaximo);
}
public void setProgresso(int intProgresso){
progress.setProgress(intProgresso);
}
public boolean cancelado(){
return progress.isCanceled();
}
}
Classe model => descompactar os arquivos
package br.com.unzip.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZipFile {
/**
* Unzip it
* @param zipFile input zip file
* @param output zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try{
//create output directory is not exists
File folder = new File(outputFolder);
if(!folder.exists()){
folder.mkdir();
}
//get the zip file content
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
Classe UnZip => principal
package br.com.unzip.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import br.com.unzip.model.UnZipFile;
public class UnZip {
private String destinationFolder = null;
public UnZip(){
}
public void ziparArquivo(String caminhoArquivoZip) {
String sourceFolder = "";
sourceFolder = caminhoArquivoZip;
if(sourceFolder != null){
destinationFolder = System.getProperty("java.io.tmpdir");
Date data = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy-HHmmss");
destinationFolder = destinationFolder + dateFormat.format(data);
System.out.println("destinationFolder: " + destinationFolder);
UnZipFile zipFolder = new UnZipFile();
zipFolder.unZipIt(sourceFolder, destinationFolder);
}
}
public String getDestinationFolder() {
return destinationFolder;
}
}
quinta-feira, 29 de maio de 2014
Zipar arquivos em Lotus Script com ls2j
Como Lotus Script não possui uma classe nativa para compactar arquivos no formato '.zip', Criei essa funcionalidade utilizando 'ls2j' para conectar na classe java.
Necessidade: O sistema deverá permitir a seleção de um arquivo no formato 'player.html' e o sistema deverá compactar toda a estrutura de diretórios do arquivo selecionado.
1º Criação de um agent Lotus Script com o código abaixo:
Option Public
Option Declare
UseLSX "*javacon"
Use "bib_zip"
Use "OpenLogFunctions" '// OpenLog para captura de erros
Sub Initialize
On Error GoTo trataerro
Dim mySession As JavaSession
Dim zipClass As JavaClass
Dim zipFileObject As JavaObject
Set mySession = New JavaSession()
Set zipClass = mySession.GetClass("br.com.zipFile.controller.ZiparArquivos")
Set zipFileObject = zipClass.CreateObject()
Dim ses_corrente As New NotesSession
Dim strDesktop As String
strDesktop = getDiretorio(ses_corrente)
Dim ws_corrente As New NotesUIWorkspace
Dim varArqHtml As Variant
varArqHtml = ws_corrente.OpenFileDialog(False, "Selecione o arquivo 'Player.html' para anexar", "Htm|*.html", strDesktop)
If IsEmpty(varArqHtml) Then
MsgBox "Operação Cancelada"
Exit Sub
End If
Dim strArqHtmlDiretorio As String
Dim strArqHtmlNomeDir As String
strArqHtmlDiretorio = varArqHtml(0)
strArqHtmlDiretorio = StrLeftBack(strArqHtmlDiretorio,"\")
strArqHtmlNomeDir = StrRightBack(strArqHtmlDiretorio,"\")
Call zipFileObject.ziparArquivo(strArqHtmlDiretorio,strArqHtmlNomeDir)
Dim returnZipPath As String
returnZipPath = zipFileObject.getZippedFilePath()
Dim iuD_corrente As NotesUIDocument
Set iuD_corrente = ws_corrente.currentDocument
Dim doc_atual As NotesDocument
Set doc_atual = iuD_corrente.Document
' //define o campo como notesrichtextitem p/poder anexar
Dim rti_anexo As NotesRichTextItem
set rti_anexo = doc_atual.Getfirstitem("ca_AnexoConvertido")
If Not rti_anexo Is Nothing Then
Call rti_anexo.Remove()
End If
Set rti_anexo = New NotesRichTextItem(doc_atual, "ca_AnexoConvertido")
Call rti_anexo.EmbedObject( EMBED_ATTACHMENT, "", returnZipPath)
Call doc_atual.Save(True,False)
doc_atual.SaveOptions = "0"
Call iuD_corrente.Close()
Call ws_corrente.editDocument(True,doc_atual,False)
Exit Sub
trataerro:
MsgBox | Erro na linha | & CStr(Erl) & | tipo | & CStr(Err) & | | & CStr(Error) , 16, |Operação Cancelada|
Call LogError()
Exit Sub
End Sub
Function getDiretorio(ses_session As NotesSession) As String
On Error GoTo trataerro
getDiretorio = ""
Dim strAux As String
strAux = Environ("HomePath")
If (Trim(strAux)<>"") Then
getDiretorio = strAux + |\Desktop|
Exit Function
End If
strAux = Environ("HOMEDRIVE")
If (Trim(strAux)<>"") Then
getDiretorio = strAux
Exit Function
End If
strAux = ses_session.GetEnvironmentString("Directory",True)
If (Trim(strAux)<>"") Then
getDiretorio = strAux
Exit Function
End If
strAux = ses_session.GetEnvironmentString("Location",True)
If (Trim(strAux)<>"") Then
getDiretorio = strAux
Exit Function
End If
trataerro:
Call AddtoStackTrace()
End Function
2º Criação da biblioteca de script 'bib_zip' em Java com os métodos p/compactar.
Classe Progresso. => Progressive dialog
package br.com.zipFile.view;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.ProgressMonitor;
public class Progresso {
ProgressMonitor progress;
public Progresso(String strMensagem, String strAlerta, int intMaximo){
JFrame frame = new JFrame();
WindowListener exitListener;
exitListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = e.getWindow();
window.setVisible(false);
window.dispose();
System.exit(0);
}
};
frame.addWindowListener(exitListener);
progress = new ProgressMonitor(frame, strMensagem, strAlerta, 0, intMaximo);
}
public void setProgresso(int intProgresso){
progress.setProgress(intProgresso);
}
public boolean cancelado(){
return progress.isCanceled();
}
}
Classe model => compactar os arquivos
package br.com.zipFile.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import br.com.zipFile.view.Progresso;
public class ZipFolder {
List
private String sourceFolder = "";
public ZipFolder(String sourceFolder){
this.sourceFolder = sourceFolder;
fileList = new ArrayList
}
public void zipIt(String zipFile){
byte[] buffer = new byte[1024];
Progresso progresso = new Progresso("Compactando arquivos...", "Aguarde...", fileList.size()-1);
int counter = 0;
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String file : this.fileList){
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(sourceFolder + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
if(progresso.cancelado()){
break;
}
progresso.setProgresso(counter);
counter++;
in.close();
}
zos.closeEntry();
zos.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
public void generateFileList(File node){
//add file only
if(node.isFile()){
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if(node.isDirectory()){
String[] subNote = node.list();
for(String filename : subNote){
generateFileList(new File(node, filename));
}
}
}
private String generateZipEntry(String file){
return file.substring(sourceFolder.length()+1, file.length());
}
}
Classe ZiparArquivos => principal
package br.com.zipFile.controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import br.com.zipFile.model.ZipFolder;
public class ZiparArquivos {
private String destinationFileName = null;
public ZiparArquivos(){
}
public void ziparArquivo(String caminhoArquivoHtml,String arquivoHtml) {
String sourceFolder = "";
String destinationFolder = "";
sourceFolder = caminhoArquivoHtml;
if(sourceFolder != null){
destinationFolder = System.getProperty("java.io.tmpdir");
Date data = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy-HHmmss");
destinationFileName = destinationFolder + arquivoHtml + "_" + dateFormat.format(data) + ".zip";
ZipFolder zipFolder = new ZipFolder(sourceFolder);
zipFolder.generateFileList(new File(sourceFolder));
zipFolder.zipIt(destinationFileName);
}
}
public String getZippedFilePath(){
return destinationFileName;
}
}
quarta-feira, 2 de abril de 2014
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("
"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.
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.
terça-feira, 31 de janeiro de 2012
Ordenar um NotesDocumentCollection por um campo
// Sorts a NotesDocumentCollection by item name
// @param col, unsorted NotesDocumentCollection
// @param iName, the name of the item to sort the collection by.
// @return sorted NotesDocumentCollection
// @author Ulrich Krause
// @version 1.0
function sortColByItemName(col:NotesDocumentCollection, iName:String) {
var rl:java.util.Vector = new java.util.Vector();
var doc:NotesDocument = col.getFirstDocument();
var tm:java.util.TreeMap = new java.util.TreeMap();
while (doc != null) {
tm.put(doc.getItemValueString(iName), doc);
doc = col.getNextDocument(doc);
}
var tCol:java.util.Collection = tm.values();
var tIt:java.util.Iterator = tCol.iterator();
while (tIt.hasNext()) {
rl.add(tIt.next());
}
return rl;
}
// @param col, unsorted NotesDocumentCollection
// @param iName, the name of the item to sort the collection by.
// @return sorted NotesDocumentCollection
// @author Ulrich Krause
// @version 1.0
function sortColByItemName(col:NotesDocumentCollection, iName:String) {
var rl:java.util.Vector = new java.util.Vector();
var doc:NotesDocument = col.getFirstDocument();
var tm:java.util.TreeMap = new java.util.TreeMap();
while (doc != null) {
tm.put(doc.getItemValueString(iName), doc);
doc = col.getNextDocument(doc);
}
var tCol:java.util.Collection = tm.values();
var tIt:java.util.Iterator = tCol.iterator();
while (tIt.hasNext()) {
rl.add(tIt.next());
}
return rl;
}
sexta-feira, 21 de janeiro de 2011
Gerar PDF a partir de um notesdocument
%REM
Versões anteriores a 7, deve executar o agente com RunOnSeerver
Ambiente nesta solução:
Trab. com um documento SALVO no client Notes e precisava exportar os textos para impressão.
A imagem anexada no cabeçhalho encontra-se em um documento notes que é setado em outra visão.
Para isso foi criado um agente(list Selection / target:none) com o código abaixo:
%END REM
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import lotus.domino.Agent;
import lotus.domino.AgentBase;
import lotus.domino.AgentContext;
import lotus.domino.Database;
import lotus.domino.DateTime;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.RichTextItem;
import lotus.domino.Session;
import lotus.domino.Stream;
import lotus.domino.View;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
//import com.lowagie.text.*;
//import com.lowagie.text.pdf.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Database db = agentContext.getCurrentDatabase();
Agent agent = agentContext.getCurrentAgent();
//System.out.println(agent.getParameterDocID());
Document doc = db.getDocumentByID(agent.getParameterDocID());
String id = doc.getUniversalID();
String filename = id+".pdf";
ByteArrayOutputStream os = new ByteArrayOutputStream(); //( PageSize.A4,esq uerda,direita,topo,rodapé)
com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4,35,35,10,35);
PdfWriter.getInstance(document, os);
String strDataTopo = "";
document.open();
document.newPage();
/***************************** MONTANDO O PDF ****************************/
//seta a visão
View visao = db.getView("vwLogo");
// seta o documento com o Logo
lotus.domino.Document docLogo = visao.getDocumentByKey("img_imagem.JPG", true);
//verifica se o documento foi setado corretamente
if (docLogo!=null){
//seta o path do anexo (campo texto)
String filepath = docLogo.getItemValueString("ASName"); //ca_labelAnexo
//seta o nome do anexo
String filesname = filepath.substring(filepath.lastIndexOf("/")+1);
//seta o anexo através do nome
EmbeddedObject file = docLogo.getAttachment(filesname);
//seta o anexo como streaming
InputStream is = file.getInputStream();
//read the inputstream in to a bytearray to pass to PDF image instance
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();
//seta o logo
Image logo = Image.getInstance(data); /* imagem setada e convertida**/
/*************** *montando o pdf **********/
// seta o campo data p/inserir no cabeçalho
try {
strDataTopo = (new SimpleDateFormat("dd/MM/yyyy")).format(((DateTime)doc.getItemValueDateTimeArray("ca_alert_data").firstElement()).toJavaDate()).toString();
} catch (NotesException e) {
strDataTopo ="";
}
//cria o cabeçalho
float[] widths1 = { 1.25f, 2.25f, 1.75f };
PdfPTable table = new PdfPTable(widths1); // 3 é referente ao número de colunas
PdfPCell c1 = new PdfPCell();
c1.setImage(logo); // <= inseri o logo na primeira coluna
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_BOTTOM); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
table.addCell(c1); //inseri a célula na tabela
c1 = new PdfPCell(new Phrase("RESERVADO"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela
c1 = new PdfPCell(new Phrase(strDataTopo));
//c1 = new PdfPCell(new Phrase(strDataTopo));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela
// com a tabela com 100% da definição da pagina
table.setWidthPercentage(100);
//adiciona a tabela no document
document.add(table); //inseri a tabela no documento ( pdf )
}
//FIM - cria o cabeçalho
Paragraph myParagraph = new Paragraph( "ALERTA REGIONAL" , new Font(Font.HELVETICA, 10, Font.BOLD));
myParagraph.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph );
document.add( new Paragraph(" ") );
Paragraph myParagraph2 = new Paragraph( "SEGURANÇA EMPRESARIAL | CONTATO: GDN1" , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_RIGHT);
document.add( myParagraph2 );
document.add( new Paragraph(" ") );
Paragraph myParagraph3 = new Paragraph( "Regional: " + doc.getItemValueString("ca_alert_regional") , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph3 );
document.add( new Paragraph(" ") );
PdfPTable table2 = new PdfPTable(1); // 3 é referente ao número de colunas
// com a tabela com 100% da definição da pagina
table2.setWidthPercentage(100);
PdfPCell c1 = new PdfPCell();
RichTextItem rti = (RichTextItem)doc.getFirstItem("ca_alert_titulo");
c1.addElement( new Paragraph( new Paragraph( rti.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)))) ;
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setBackgroundColor(new Color(225,225,225)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_LEFT); //alinhamento Horizontal
table2.addCell(c1); //inseri a célula na tabela
document.add(table2);
RichTextItem rti2 = (RichTextItem)doc.getFirstItem("ca_alert_corpo");
document.add( new Paragraph( rti2.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)) );
document.add( new Paragraph(" ") );
document.close();
/***************************** CRIA O DOCUMENTO TEMPORÁRIO COM O ANEXO ****************************/
Document docTemp = db.createDocument();
docTemp.appendItemValue("Form", "Frm_TempAnexo");
docTemp.appendItemValue("ca_docId_docPai",doc.getUniversalID());
docTemp.appendItemValue("ca_Author",session.getUserName());
docTemp.appendItemValue("ca_excluir","0");
docTemp.save(true,true);
//Put the contents of the text field in to a Notes Stream!
Stream stream=session.createStream();
stream.write( os.toByteArray() );
//Attach file here
if ( !docTemp.isNewNote() )
docTemp.removeItem("Files");
MIMEEntity m = docTemp.createMIMEEntity("Files"); //if no param -- creates a field called Body (so one can't already be on form!)
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("attachment;filename=\""+filename+"\"");
m.setContentFromBytes(stream, "application/pdf", MIMEEntity.ENC_IDENTITY_BINARY); //ENC_BASE64);
m.decodeContent();
//Following call to doc.save() is NEEDED to commit the MIME to the doc
//even when we're in a WQS doc. Weird?!
//To allow Anonymous users to do so we need to add them to an Authors field (see Form). Even weirder.
docTemp.save(true, true);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Versões anteriores a 7, deve executar o agente com RunOnSeerver
Ambiente nesta solução:
Trab. com um documento SALVO no client Notes e precisava exportar os textos para impressão.
A imagem anexada no cabeçhalho encontra-se em um documento notes que é setado em outra visão.
Para isso foi criado um agente(list Selection / target:none) com o código abaixo:
%END REM
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import lotus.domino.Agent;
import lotus.domino.AgentBase;
import lotus.domino.AgentContext;
import lotus.domino.Database;
import lotus.domino.DateTime;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.RichTextItem;
import lotus.domino.Session;
import lotus.domino.Stream;
import lotus.domino.View;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
//import com.lowagie.text.*;
//import com.lowagie.text.pdf.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Database db = agentContext.getCurrentDatabase();
Agent agent = agentContext.getCurrentAgent();
//System.out.println(agent.getParameterDocID());
Document doc = db.getDocumentByID(agent.getParameterDocID());
String id = doc.getUniversalID();
String filename = id+".pdf";
ByteArrayOutputStream os = new ByteArrayOutputStream(); //( PageSize.A4,esq uerda,direita,topo,rodapé)
com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4,35,35,10,35);
PdfWriter.getInstance(document, os);
String strDataTopo = "";
document.open();
document.newPage();
/***************************** MONTANDO O PDF ****************************/
//seta a visão
View visao = db.getView("vwLogo");
// seta o documento com o Logo
lotus.domino.Document docLogo = visao.getDocumentByKey("img_imagem.JPG", true);
//verifica se o documento foi setado corretamente
if (docLogo!=null){
//seta o path do anexo (campo texto)
String filepath = docLogo.getItemValueString("ASName"); //ca_labelAnexo
//seta o nome do anexo
String filesname = filepath.substring(filepath.lastIndexOf("/")+1);
//seta o anexo através do nome
EmbeddedObject file = docLogo.getAttachment(filesname);
//seta o anexo como streaming
InputStream is = file.getInputStream();
//read the inputstream in to a bytearray to pass to PDF image instance
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();
//seta o logo
Image logo = Image.getInstance(data); /* imagem setada e convertida**/
/*************** *montando o pdf **********/
// seta o campo data p/inserir no cabeçalho
try {
strDataTopo = (new SimpleDateFormat("dd/MM/yyyy")).format(((DateTime)doc.getItemValueDateTimeArray("ca_alert_data").firstElement()).toJavaDate()).toString();
} catch (NotesException e) {
strDataTopo ="";
}
//cria o cabeçalho
float[] widths1 = { 1.25f, 2.25f, 1.75f };
PdfPTable table = new PdfPTable(widths1); // 3 é referente ao número de colunas
PdfPCell c1 = new PdfPCell();
c1.setImage(logo); // <= inseri o logo na primeira coluna
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_BOTTOM); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
table.addCell(c1); //inseri a célula na tabela
c1 = new PdfPCell(new Phrase("RESERVADO"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela
c1 = new PdfPCell(new Phrase(strDataTopo));
//c1 = new PdfPCell(new Phrase(strDataTopo));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela
// com a tabela com 100% da definição da pagina
table.setWidthPercentage(100);
//adiciona a tabela no document
document.add(table); //inseri a tabela no documento ( pdf )
}
//FIM - cria o cabeçalho
Paragraph myParagraph = new Paragraph( "ALERTA REGIONAL" , new Font(Font.HELVETICA, 10, Font.BOLD));
myParagraph.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph );
document.add( new Paragraph(" ") );
Paragraph myParagraph2 = new Paragraph( "SEGURANÇA EMPRESARIAL | CONTATO: GDN1" , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_RIGHT);
document.add( myParagraph2 );
document.add( new Paragraph(" ") );
Paragraph myParagraph3 = new Paragraph( "Regional: " + doc.getItemValueString("ca_alert_regional") , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph3 );
document.add( new Paragraph(" ") );
PdfPTable table2 = new PdfPTable(1); // 3 é referente ao número de colunas
// com a tabela com 100% da definição da pagina
table2.setWidthPercentage(100);
PdfPCell c1 = new PdfPCell();
RichTextItem rti = (RichTextItem)doc.getFirstItem("ca_alert_titulo");
c1.addElement( new Paragraph( new Paragraph( rti.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)))) ;
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setBackgroundColor(new Color(225,225,225)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_LEFT); //alinhamento Horizontal
table2.addCell(c1); //inseri a célula na tabela
document.add(table2);
RichTextItem rti2 = (RichTextItem)doc.getFirstItem("ca_alert_corpo");
document.add( new Paragraph( rti2.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)) );
document.add( new Paragraph(" ") );
document.close();
/***************************** CRIA O DOCUMENTO TEMPORÁRIO COM O ANEXO ****************************/
Document docTemp = db.createDocument();
docTemp.appendItemValue("Form", "Frm_TempAnexo");
docTemp.appendItemValue("ca_docId_docPai",doc.getUniversalID());
docTemp.appendItemValue("ca_Author",session.getUserName());
docTemp.appendItemValue("ca_excluir","0");
docTemp.save(true,true);
//Put the contents of the text field in to a Notes Stream!
Stream stream=session.createStream();
stream.write( os.toByteArray() );
//Attach file here
if ( !docTemp.isNewNote() )
docTemp.removeItem("Files");
MIMEEntity m = docTemp.createMIMEEntity("Files"); //if no param -- creates a field called Body (so one can't already be on form!)
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("attachment;filename=\""+filename+"\"");
m.setContentFromBytes(stream, "application/pdf", MIMEEntity.ENC_IDENTITY_BINARY); //ENC_BASE64);
m.decodeContent();
//Following call to doc.save() is NEEDED to commit the MIME to the doc
//even when we're in a WQS doc. Weird?!
//To allow Anonymous users to do so we need to add them to an Authors field (see Form). Even weirder.
docTemp.save(true, true);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compactar arquivos com Notes 6
http://searchdomino.techtarget.com/tip/1,289483,sid4_gci1002690,00.html
LotusScript does not have a native class for compressing files to .zip format. In this tip, I'll show you how change that, if you are running Notes or Domino R6 (or newer), by using the ability of LotusScript to make calls to functionality that is available in the Java language. This is done using LS2J -- which is documented in Designer Help.
I have an agent that holds the following code in Initialize:
Sub Initialize
Dim js As JAVASESSION
Dim zipClass As JAVACLASS
Dim zipFileObject As JavaObject
Dim varFileToZip As String, varOutFilePath
As String, returnCode As String
Set js = New JAVASESSION
Set zipClass = js.GetClass("ZipFile")
Set zipFileObject = zipClass.CreateObject
varFileToZip = "c:tempdocument.doc"
varOutFilePath = "c:tempthezipfile.zip"
returnCode = zipFileObject.zipMyFile
(varFileToZip, varOutFilePath)
'Calling the zip function
If Not returnCode = "OK" Then
Print "An Error occurred"
Else
Print "Zip went OK"
End If
End Sub
In the Options of the agent I have the following:
Uselsx "*javacon" 'Which lets you use
Java from LotusScript
Use "ZipFile" 'A Java library that holds
a function to do zipping
Below is the Java Library that makes it possible to zip a file. You create a Java Library in the Designer in Shared code -> Script Libraries, click New Java Library, remove the few lines of code that you get as a help for getting started, and paste the code below. Save and call the library "ZipFile."
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) {
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);
// 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";
}
}
Credit goes to this article that helped me get zipping to work: Zip meets Java from Devshed.
LotusScript does not have a native class for compressing files to .zip format. In this tip, I'll show you how change that, if you are running Notes or Domino R6 (or newer), by using the ability of LotusScript to make calls to functionality that is available in the Java language. This is done using LS2J -- which is documented in Designer Help.
I have an agent that holds the following code in Initialize:
Sub Initialize
Dim js As JAVASESSION
Dim zipClass As JAVACLASS
Dim zipFileObject As JavaObject
Dim varFileToZip As String, varOutFilePath
As String, returnCode As String
Set js = New JAVASESSION
Set zipClass = js.GetClass("ZipFile")
Set zipFileObject = zipClass.CreateObject
varFileToZip = "c:tempdocument.doc"
varOutFilePath = "c:tempthezipfile.zip"
returnCode = zipFileObject.zipMyFile
(varFileToZip, varOutFilePath)
'Calling the zip function
If Not returnCode = "OK" Then
Print "An Error occurred"
Else
Print "Zip went OK"
End If
End Sub
In the Options of the agent I have the following:
Uselsx "*javacon" 'Which lets you use
Java from LotusScript
Use "ZipFile" 'A Java library that holds
a function to do zipping
Below is the Java Library that makes it possible to zip a file. You create a Java Library in the Designer in Shared code -> Script Libraries, click New Java Library, remove the few lines of code that you get as a help for getting started, and paste the code below. Save and call the library "ZipFile."
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) {
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);
// 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";
}
}
Credit goes to this article that helped me get zipping to work: Zip meets Java from Devshed.
Extrair arquivos com Java
link: http://www.devshed.com/c/a/Java/Zip-Meets-Java/2/
So we can create zip files with Java. Can we extract them? Listing 2 shows an example Java class that can do just that. Let’s cover what’s going on in the class, as it might not be that obvious to the java.util.zip API newcomer.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUncompressExample
{
// specify buffer size for extraction
static final int BUFFER = 2048;
public static void main(String[] args)
{
try
{
System.out.println("Example of ZIP file decompression.");
// Specify file to decompress
String inFileName = "c:\example.zip";
// Specify destination where file will be unzipped
String destinationDirectory = "c:\temp\";
File sourceZipFile = new File(inFileName);
File unzipDestinationDirectory = new File(destinationDirectory);
// Open Zip file for reading
ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
// Create an enumeration of the entries in the zip file
Enumeration zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
System.out.println("Extracting: " + entry);
File destFile =
new File(unzipDestinationDirectory, currentEntry);
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
// extract file if not a directory
if (!entry.isDirectory())
{
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1)
{
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
zipFile.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The ZipUncompressExample class unzips a file called example.zip and extracts it to a destination directory called d:temp. We first open the source zip file. From our ZipFile object, we can use the entires() method to obtain an Enumeration which contains ZipEntry objects. These individual ZipEntry objects represent the entries which make up the Zip file.
I then use a while loop to cycle through the entries of our Zip file. As we process each ZipEntry object, we have to check and see if the zip entry in question has the needed housing directory structure in place. If the needed directories are not created, they are established. We use the getParentFile method of the File class to obtain the parent directory structure. If the current zip entry is not a directory (i.e., a file), we write the file to disk in the corresponding housing directory. This process is continued until each entry in the Zip file is processed.
So we can create zip files with Java. Can we extract them? Listing 2 shows an example Java class that can do just that. Let’s cover what’s going on in the class, as it might not be that obvious to the java.util.zip API newcomer.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUncompressExample
{
// specify buffer size for extraction
static final int BUFFER = 2048;
public static void main(String[] args)
{
try
{
System.out.println("Example of ZIP file decompression.");
// Specify file to decompress
String inFileName = "c:\example.zip";
// Specify destination where file will be unzipped
String destinationDirectory = "c:\temp\";
File sourceZipFile = new File(inFileName);
File unzipDestinationDirectory = new File(destinationDirectory);
// Open Zip file for reading
ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
// Create an enumeration of the entries in the zip file
Enumeration zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
System.out.println("Extracting: " + entry);
File destFile =
new File(unzipDestinationDirectory, currentEntry);
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
// extract file if not a directory
if (!entry.isDirectory())
{
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1)
{
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
zipFile.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The ZipUncompressExample class unzips a file called example.zip and extracts it to a destination directory called d:temp. We first open the source zip file. From our ZipFile object, we can use the entires() method to obtain an Enumeration which contains ZipEntry objects. These individual ZipEntry objects represent the entries which make up the Zip file.
I then use a while loop to cycle through the entries of our Zip file. As we process each ZipEntry object, we have to check and see if the zip entry in question has the needed housing directory structure in place. If the needed directories are not created, they are established. We use the getParentFile method of the File class to obtain the parent directory structure. If the current zip entry is not a directory (i.e., a file), we write the file to disk in the corresponding housing directory. This process is continued until each entry in the Zip file is processed.
Assinar:
Postagens (Atom)