Home > Domino Tips > Developer > Java > Shrink Lotus Notes databases with many attachments
Domino Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

JAVA

Shrink Lotus Notes databases with many attachments


Jairo Abraham Bernal Villanueva
10.09.2007
Rating: -3.17- (out of 5)


Lotus Notes, Domino, Workplace and WebSphere tips and advice
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


Use this Java code to reduce the size of Lotus Notes databases with large amounts of attachments.
Related resources from SearchDomino.com:
Tip: Reduce the size of your Lotus Notes database

Expert Advice: Calculating the size of a Lotus Notes database

FAQ: Java for Lotus Notes and Domino

Java for Lotus Notes Domino Reference Center

Suppose that there 
is a form which has 
a RichText called Body.
We must make a 
Script Library called 
ZipHelper whit next code:
//// Begin ZipHelper code
import java.io.*; 
import java.util.*;
import java.util.zip.*;

public class ZipHelper
{
final int BUFFER = 2048;

public String getTempDirectory()
{
return System.getProperty("java.io.tmpdir");
}
 
public String zipMultipleFiles(Vector 
filesToZip, 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);
Enumeration e = filesToZip.elements();
while (e.hasMoreElements())
{
String fileToZip = (String)e.nextElement();
if((new File(fileToZip)).exists())
{
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";
 }
 
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";
 } 
 
public String unzipMyFile(String zipFilePath, 
String pathToUnzip) 
 {
try
{
zipFilePath = zipFilePath.replace('\', '/');
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream
( zipFilePath );   
ZipInputStream zis = new ZipInputStream
(new BufferedInputStream(fis));
ZipEntry entry;
int count;
byte data[] = new byte[BUFFER];
pathToUnzip = pathToUnzip.replace('\', '/');
if(pathToUnzip.charAt(pathToUnzip.length()-1) != '/')
pathToUnzip += "/";

while((entry = zis.getNextEntry()) != null) 
{
if( entry.isDirectory() ) //Directory
 {
   (new File(pathToUnzip + entry.getName())).mkdir();
     continue;
   }
  else //File
  {
  String newfile = pathToUnzip + entry.getName();
                   
   // write the files to the disk
   FileOutputStream fos = new FileOutputStream
(pathToUnzip + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
  while ((count = zis.read(data, 0, BUFFER)) != -1)
 {
 dest.write(data, 0, count);
  }
 dest.flush();
   dest.close();
      }
}
zis.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";
       }
catch(Exception e) 
  {
e.printStackTrace();
return "UNKNOWN_ERROR";
  }
return "OK";
 }
}
//// End ZipHelper code

Next we must create a Java agent 
called ZipAttachments triggered 
On event "Agent List Selection" whith Next Code

//// Begin ZipAttachments agent code
import lotus.domino.*;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;

public class JavaAgent extends 
AgentBase {

public void NotesMain() {

try {
ZipHelper zipHelper = new ZipHelper();
Session session = getSession();
String tempDir = System.getProperty
("java.io.tmpdir");
String zipFile = new String
( "Attachments.zip" );
AgentContext agentContext = 
session.getAgentContext();

Database db = agentContext.
getCurrentDatabase();
Document doc = agentContext.
getDocumentContext();
RichTextItem body = (RichTextItem)
doc.getFirstItem("Body");
Vector v = body.getEmbeddedObjects();
Vector vNames = new Vector();
Enumeration e = v.elements();
while (e.hasMoreElements())
 {
EmbeddedObject eo = 
(EmbeddedObject)e.nextElement();
if (eo.getType() == 
EmbeddedObject.EMBED_ATTACHMENT)
 {
eo.extractFile( tempDir + eo.getSource() );
vNames.add( tempDir + eo.getSource() );
eo.remove();
doc.save(true, false);
}
 }
zipHelper.zipMultipleFiles(vNames, 
tempDir + zipFile);
if((new File(tempDir +  zipFile)).exists())
 {
body.embedObject(EmbeddedObject.
EMBED_ATTACHMENT, null, tempDir 
+  zipFile,  zipFile);
(new File(tempDir + zipFile)).delete();
 }
doc.save(true, false);
e = vNames.elements();
while(e.hasMoreElements())
{
String fileName = (String)e.nextElement();
if((new File(fileName)).exists())
 {
(new File(fileName)).delete();
}
 }
} catch(Exception e) {
e.printStackTrace();
  }
 }
}
//// End ZipAttachments agent code

Note: Before saving, we must click "Edit Project" and add: (Library)ZipHelper.

In the form PostSave event we must enter:

@Command
([ToolsRunMacro]; 
"(ZipAttachments)" );
@Command([CloseWindow])

Do you have comments on this tip? Let us know.

This tip was submitted to the SearchDomino.com tip library by member Jairo Villanueva. Please let others know how useful it is via the rating scale below. Do you have a useful Lotus Notes, Domino, Workplace or WebSphere tip or code snippet to share? Submit it to our monthly tip contest and you could win a prize.

Rate this Tip
To rate tips, you must be a member of SearchDomino.com.
Register now to start rating these tips. Log in if you are already a member.




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


RELATED CONTENT
Java for Lotus Notes Domino
Java code shortens strings in a SQL table
How to execute a stored procedure in Lotus Notes Domino using Java
Top 10 Lotus Notes Domino programming and development tips of 2007
How to return an HTML representation of a Lotus Notes rich-text field
Converting Lotus Notes Domino Web pages to PDF files with a Java agent
Developing Eclipse plug-ins for Lotus Notes and Domino -- 7 tips in 7 minutes
A bevy of Notes/Domino development tips
Converting Web pages to images using Java
Creating Microsoft Word documents from Lotus Notes
Sending and logging faxes from Lotus Notes and Domino

Java
Java code shortens strings in a SQL table
How to execute a stored procedure in Lotus Notes Domino using Java
How to return an HTML representation of a Lotus Notes rich-text field
Converting Lotus Notes Domino Web pages to PDF files with a Java agent
A bevy of Notes/Domino development tips
Converting Web pages to images using Java
Creating Microsoft Word documents from Lotus Notes
FAQ: Java for Lotus Notes and Domino
Automatically scan Lotus Notes database document attachments for viruses
Creating PDF documents from Lotus Notes

Lotus Notes Domino Database Management
Lotus Notes Domino database management and maintenance pointers
Lotus Notes access error: 'database is not opened yet'
Programmatically replace the design of Lotus Notes databases
Add a program doc to compact Lotus Notes databases automatically
Set a value in a field existing in another Lotus Notes database
'Illegal circular use: Audit Trail' error when opening Lotus Notes docs
Remove orphaned Lotus Notes documents on Domino databases with a 'virtual delete'
Copy Lotus Notes databases from the Domino Server console command line
Tutorial: How to import data into Lotus Notes -- without programming
Easily show and hide layers in a Lotus Notes database

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.

HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersDomino IT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Reprints  |  Site Map




All Rights Reserved, Copyright 1999 - 2008, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts