how to update metadata of docx file using apache poi in java? - java

I am not getting how to update meta data (title,subject,author etc..) for docx file using apache poi.
I have tried it for a doc file using apache poi:
File poiFilesystem = new File(file_path1);
/* Open the POI filesystem. */
InputStream is = new FileInputStream(poiFilesystem);
POIFSFileSystem poifs = new POIFSFileSystem(is);
is.close();
/* Read the summary information. */
DirectoryEntry dir = poifs.getRoot();
SummaryInformation si;
try
{
DocumentEntry siEntry = (DocumentEntry)
dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
DocumentInputStream dis = new DocumentInputStream(siEntry);
PropertySet ps = new PropertySet(dis);
dis.close();
si = new SummaryInformation(ps);
}
catch (FileNotFoundException ex)
{
/* There is no summary information yet. We have to create a new
* one. */
si = PropertySetFactory.newSummaryInformation();
}
si.setAuthor("xzy");
System.out.println("Author changed to " + si.getAuthor() + ".");
si.setSubject("mysubject");
si.setTitle("mytitle");

Below work with POI-3.10. You can set some metadata with PackageProperties:
import java.util.Date;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.openxml4j.util.Nullable;
class SetDOCXMetadata{
public static void main(String[] args){
try{
OPCPackage opc = OPCPackage.open("metadata.docx");
PackageProperties pp = opc.getPackageProperties();
Nullable<String> foo = pp.getLastModifiedByProperty();
System.out.println(foo.hasValue()?foo.getValue():"empty");
//Set some properties
pp.setCreatorProperty("M Kazarian");
pp.setLastModifiedByProperty("M Kazarian " + System.currentTimeMillis());
pp.setModifiedProperty(new Nullable<Date>(new Date()));
pp.setTitleProperty("M Kazarian document");
opc.close();
} catch (Exception e) {}
}
}

Related

File not found in Directory (Static PDF attachment)

My requirement is with a generic PDF i have to attach a static PDF for an email , i can attach the generic PDF without any issues , but it is giving me an issue with static PDF while fetching it from the directory, i have tried several ways could you please assist ....
Below is error and the code related to it....
Error :java.io.FileNotFoundException: /mnt/DGB/Correspondence/Systems/PROD_DOCS/How_to_access_member_information.pdf (No such file or directory)
Code :
try {
File pdfFile = new File("//mnt/DGB/Correspondence/Systems/PROD_DOCS/How_to_access_member_information.pdf");
byte[] bytesArray = new byte[(int) pdfFile.length()];
FileInputStream fis = new FileInputStream(pdfFile);
fis.read(bytesArray); //read file into bytes[]
fis.close();
String registerId = notificationEngineService.registerFileOnNe("application/pdf", "How_to_access_member_information.pdf", bytesArray);
System.out.println("registerId 1=============================== " + registerId);
notificationEngineService.sendRegisteredAttViaNe(registerId, emailBody, dispInfo);
} catch (Exception e) {
System.out.println("Exception 10============================================================");
e.printStackTrace();
}
try {
File pdfFile = new File("\\\\dcpcifs01\\DGB\\Correspondence\\Systems\\PROD_DOCS\\How_to_access_member_information.pdf");
byte[] bytesArray = new byte[(int) pdfFile.length()];
FileInputStream fis = new FileInputStream(pdfFile);
fis.read(bytesArray); //read file into bytes[]
fis.close();
String registerId = notificationEngineService.registerFileOnNe("application/pdf", "How_to_access_member_information.pdf", bytesArray);
System.out.println("registerId 2=============================== " + registerId);
notificationEngineService.sendRegisteredAttViaNe(registerId, emailBody, dispInfo);
} catch (Exception e) {
System.out.println("Exception 10============================================================");
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
throw new GroupRiskSystemException(ExceptionCode.COMPASS_ERROR.name());
}
return "";
}
private void sendEmail(MbsMembers memberObject) {
try {
System.out.println(" ======================Start0=================================== ");
za.co.discoverygrouprisk.common.jaxb.email.AttachmentType attachmentType = new za.co.discoverygrouprisk.common.jaxb.email.AttachmentType();
attachmentType.setMember(new MemberType());
attachmentType.setCamundaProcessId("0");
attachmentType.setFileName("How_to_access_member_information.pdf");
attachmentType.setChildBusinessKey(0l);
attachmentType.setNeID(0l);
DGRMultiAttachmentEmailDetailV01 emailDetail = new DGRMultiAttachmentEmailDetailV01();
SchemeDataType schemeDataType = new SchemeDataType();
SchemeType schemeType = new SchemeType();
SchemeNumberType schemeNumberType = new SchemeNumberType();
schemeNumberType.setValue(01);
schemeType.setSchemeNumber(schemeNumberType);
schemeDataType.setScheme(schemeType);
emailDetail.setSchemeData(schemeDataType);
EmailDataType emailDataType = new EmailDataType();
EmailType emailType = new EmailType();
emailType.setSubject("How to access member information");
emailType.setFromAddress("groupinfo#discovery.co.za");
emailType.setToAddress(memberObject.getEmailAddress());
emailDataType.setEmail(emailType);
emailDetail.setEmailData(emailDataType);
AttachmentDataType attachmentDataType = new AttachmentDataType();
// attachmentDataType.setLocation("//mnt/DGB/Correspondence/Systems/PROD_DOCS/");
attachmentDataType.setLocation("\\\\dcpcifs01\\DGB\\Correspondence\\Systems\\PROD_DOCS\\");
//mnt/DGB/Correspondence/2020/QA/MEMBER_REQUIREMENT_LETTER
attachmentDataType.setParentBusinessKey(01);
attachmentDataType.getAttachment().add(attachmentType);
emailDetail.setAttachmentData(attachmentDataType);
EmailDataSource adHocDS = new AdHocEmailDataSource(emailDetail);
String emailBody = createEmailBody(memberObject);
StandardEmailTemplate template = new StandardEmailTemplate(emailBody);
Email email = new StandardEmail(adHocDS, template);
email.createEmail();
email.sendEmail();
System.out.println(" ======================End0=================================== ");
} catch (Exception e) {
System.out.println(" ======================Exception0=================================== ");
e.printStackTrace();
}
}
Use below :
File pdfFile = new File("/mnt/DGB/Correspondence/Systems/PROD_DOCS/How_to_access_member_information.pdf");
Adding the below :
Create a directory under user home directory say : /home/user_name/java-pdf.
Then try the below code once to check if your code is able to access the file:
File homedir = new File(System.getProperty("user.home"));
File pdfFile = new File(homedir, "java-pdf/How_to_access_member_information.pdf");
The above code runs fine for me.

Unable to recover correct file extension after creating .gz through GZipOutputStream

I have the contents I want to write to a file saved in Strings in my Java program. I need o write them to a .txt file and then compress them into a .gz archive. I'm able to do all of this, but when I extract the file from the .gz archive, the extracted file no longer bear's the .txt file extension.
This is my code below:
private void fillFileBody(OutputStream outputStream) throws IOException {
Scanner scanner = new Scanner(new ByteArrayInputStream(this.fileBody.getBytes()));
while(scanner.hasNextLine()){
outputStream.write((scanner.nextLine() + "\n").getBytes());
}
scanner.close();
}
public void writeFileContentsToDisk(){
GZIPOutputStream gZipOutStream = null;
FileOutputStream initialTxtFileOutStream = null;
FileInputStream initialTxtFileInStream = null;
String txtFile = this.fileName + ".txt";
try {
initialTxtFileOutStream = new FileOutputStream(txtFile);
initialTxtFileOutStream.write((this.fileHeader).getBytes());
fillFileBody(initialTxtFileOutStream);
initialTxtFileOutStream.write(this.fileTrailer.getBytes());
initialTxtFileInStream = new FileInputStream(txtFile);
gZipOutStream = new GZIPOutputStream(new FileOutputStream(this.fileName + ".gz"));
byte[] buffer = new byte[1024];
int length;
while ((length = initialTxtFileInStream.read(buffer)) > 0) {
gZipOutStream.write(buffer, 0, length);
}
} catch (Exception e) {
LOGGER.error("Error writing file: " + Logger.getStackTrace(e));
}
try {
gZipOutStream.close();
initialTxtFileOutStream.close();
initialTxtFileInStream.close();
} catch (IOException e) {
LOGGER.warn("Error closing i/o streams involved in writing file: " + Logger.getStackTrace(e));
}
}
I wrote the sample code below and used x.c as input from my working directory. x.c.gz was the output file. I used gunzip on x.c.gz and it produced a file with the name x.c and so it seemed to work fine.
package compress;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
/**
*
* #author srikanthn
*/
public class Compress {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
compressFile(args[0]);
}
public static void compressFile(String file){
GZIPOutputStream gZipOutStream = null;
FileInputStream initialTxtFileInStream = null;
String txtFile = file;
try {
initialTxtFileInStream = new FileInputStream(txtFile);
gZipOutStream = new GZIPOutputStream(new FileOutputStream(txtFile+ ".gz"));
byte[] buffer = new byte[1024];
int length;
while ((length = initialTxtFileInStream.read(buffer)) > 0) {
gZipOutStream.write(buffer, 0, length);
}
} catch (IOException e) {
System.out.println("Error writing file: " + e.getStackTrace());
}
try {
gZipOutStream.close();
initialTxtFileInStream.close();
} catch (IOException e) {
System.out.println("Error closing i/o streams involved in writing file: " + e.getStackTrace());
}
}
}

Read embedded pdf file in excel using Java

I am new to Java programming. My current project requires me to read embedded(ole) files in an excel sheet and get text contents in them. Examples for reading embedded word file worked fine, however I am unable to find help reading an embedded pdf file. Tried few things by looking at similar examples.... which didn't work out.
http://poi.apache.org/spreadsheet/quick-guide.html#Embedded
I have code below, probably with help I can get in right direction. I have used Apache POI to read embedded files in excel and pdfbox to parse pdf data.
public class ReadExcel1 {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
POIFSFileSystem fs = new POIFSFileSystem(file);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
String oleName = obj.getOLE2ClassName();
if(oleName.equals("Acrobat Document")){
System.out.println("Acrobat reader document");
try{
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
for (Iterator<Entry> entries = dn.getEntries(); entries.hasNext();) {
DocumentEntry nativeEntry = (DocumentEntry) dn.getEntry("CONTENTS");
byte[] data = new byte[nativeEntry.getSize()];
ByteArrayInputStream bao= new ByteArrayInputStream(data);
PDFParser pdfparser = new PDFParser(bao);
pdfparser.parse();
COSDocument cosDoc = pdfparser.getDocument();
PDFTextStripper pdfStripper = new PDFTextStripper();
PDDocument pdDoc = new PDDocument(cosDoc);
pdfStripper.setStartPage(1);
pdfStripper.setEndPage(2);
System.out.println("Text from the pdf "+pdfStripper.getText(pdDoc));
}
}catch(Exception e){
System.out.println("Error reading "+ e.getMessage());
}finally{
System.out.println("Finally ");
}
}else{
System.out.println("nothing ");
}
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the output in eclipse
Acrobat reader document
Error reading Error: End-of-File, expected line
Finally
nothing
The PDF weren't OLE 1.0 packaged, but somehow differently embedded - at least the extraction worked for me.
This is not a general solution, because it depends on how the embedding application names the entries ... of course for PDFs you could check all DocumentNode-s for the magic number "%PDF" - and in case of OLE 1.0 packaged elements this needs to be done differently ...
I think, the real filename of the pdf is somewhere hidden in the \1Ole or CompObj entries, but for the example and apparently for your use case that's not necessary to determine.
import java.io.*;
import java.net.URL;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.util.IOUtils;
public class EmbeddedPdfInExcel {
public static void main(String[] args) throws Exception {
NPOIFSFileSystem fs = new NPOIFSFileSystem(new URL("http://jamesshaji.com/sample.xls").openStream());
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
for (HSSFObjectData obj : wb.getAllEmbeddedObjects()) {
String oleName = obj.getOLE2ClassName();
DirectoryNode dn = (DirectoryNode)obj.getDirectory();
if(oleName.contains("Acro") && dn.hasEntry("CONTENTS")){
InputStream is = dn.createDocumentInputStream("CONTENTS");
FileOutputStream fos = new FileOutputStream(obj.getDirectory().getName()+".pdf");
IOUtils.copy(is, fos);
fos.close();
is.close();
}
}
fs.close();
}
}

How to get file summary information with Java/Apache POI

i'am trying to get the summary information from file with JAVA and I can't found anything. I tried with org.apache.poi.hpsf.* .
I need Author, Subject, Comments, Keywords and Title.
File rep = new File("C:\\Cry_ReportERP006.rpt");
/* Read a test document <em>doc</em> into a POI filesystem. */
final POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(rep));
final DirectoryEntry dir = poifs.getRoot();
DocumentEntry dsiEntry = null;
try
{
dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
catch (FileNotFoundException ex)
{
/*
* A missing document summary information stream is not an error
* and therefore silently ignored here.
*/
}
/*
* If there is a document summry information stream, read it from
* the POI filesystem.
*/
if (dsiEntry != null)
{
final DocumentInputStream dis = new DocumentInputStream(dsiEntry);
final PropertySet ps = new PropertySet(dis);
final DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);
final SummaryInformation si = new SummaryInformation(ps);
/* Execute the get... methods. */
System.out.println(si.getAuthor());
As explained in the POI overview at http://poi.apache.org/overview.html there are more types of file parsers.
The following examples extract the Author/Creator from 2003 office files:
public static String parseOLE2FileAuthor(File file) {
String author=null;
try {
FileInputStream stream = new FileInputStream(file);
POIFSFileSystem poifs = new POIFSFileSystem(stream);
DirectoryEntry dir = poifs.getRoot();
DocumentEntry siEntry = (DocumentEntry)dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
DocumentInputStream dis = new DocumentInputStream(siEntry);
PropertySet ps = new PropertySet(dis);
SummaryInformation si = new SummaryInformation(ps);
author=si.getAuthor();
stream.close();
} catch (IOException ex) {
ex.getStackTrace();
} catch (NoPropertySetStreamException ex) {
ex.getStackTrace();
} catch (MarkUnsupportedException ex) {
ex.getStackTrace();
} catch (UnexpectedPropertySetTypeException ex) {
ex.getStackTrace();
}
return author;
}
For docx,pptx,xlsx the POI has specialized classes.
Example for .docx file:
public static String parseDOCX(File file){
String author=null;
FileInputStream stream;
try {
stream = new FileInputStream(file);
XWPFDocument docx = new XWPFDocument(stream);
CoreProperties props = docx.getProperties().getCoreProperties();
author=props.getCreator();
stream.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return author;
}
Use for PPTX use XMLSlideShow or XMLWorkbook instead of XMLDocument.
Please find the sample code here- Appache POI how to
In brief, you can a listener MyPOIFSReaderListener:
SummaryInformation si = (SummaryInformation)
PropertySetFactory.create(event.getStream());
String title = si.getTitle();
String Author= si.getLastAuthor();
......
and register it as :
POIFSReader r = new POIFSReader();
r.registerListener(new MyPOIFSReaderListener(),
"\005SummaryInformation");
r.read(new FileInputStream(filename));
for 2003 office files, you can use classes inherited from POIDocument. here is an example for doc file:
FileInputStream in = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(in);
author = doc.getSummaryInformation().getAuthor();
and HSLFSlideShowImpl for ppt,
HSSFWorkbook for xls,
HDGFDiagram for vsd.
there are many other file information within the SummaryInformation class.
for 2007 or above office file, see the answer of #Dragos Catalin Trieanu

Password protected zip file in java

I have created zip file using java as below snippet
import java.io.*;
import java.util.zip.*;
public class ZipCreateExample {
public static void main(String[] args) throws IOException {
System.out.print("Please enter file name to zip : ");
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
String filesToZip = input.readLine();
File f = new File(filesToZip);
if(!f.exists()) {
System.out.println("File not found.");
System.exit(0);
}
System.out.print("Please enter zip file name : ");
String zipFileName = input.readLine();
if (!zipFileName.endsWith(".zip"))
zipFileName = zipFileName + ".zip";
byte[] buffer = new byte[18024];
try {
ZipOutputStream out = new ZipOutputStream
(new FileOutputStream(zipFileName));
out.setLevel(Deflater.DEFAULT_COMPRESSION);
FileInputStream in = new FileInputStream(filesToZip);
out.putNextEntry(new ZipEntry(filesToZip));
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
out.close();
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
System.exit(0);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(0);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
}
}
Now I want when I click on the zip file it should prompt me to type password and then decompress the zip file.
Please any help,How should I go further?
Try the following code which is based on Zip4j:
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
public class Zipper
{
private String password;
private static final String EXTENSION = "zip";
public Zipper(String password)
{
this.password = password;
}
public void pack(String filePath) throws ZipException
{
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(password);
String baseFileName = FilenameUtils.getBaseName(filePath);
String destinationZipFilePath = baseFileName + "." + EXTENSION;
ZipFile zipFile = new ZipFile(destinationZipFilePath);
zipFile.addFile(new File(filePath), zipParameters);
}
public void unpack(String sourceZipFilePath, String extractedZipFilePath) throws ZipException
{
ZipFile zipFile = new ZipFile(sourceZipFilePath + "." + EXTENSION);
if (zipFile.isEncrypted())
{
zipFile.setPassword(password);
}
zipFile.extractAll(extractedZipFilePath);
}
}
FilenameUtils is from Apache Commons IO.
Example usage:
public static void main(String[] arguments) throws ZipException
{
Zipper zipper = new Zipper("password");
zipper.pack("encrypt-me.txt");
zipper.unpack("encrypt-me", "D:\\");
}
Standard Java API does not support password protected zip files. Fortunately good guys have already implemented such ability for us. Please take a look on this article that explains how to create password protected zip.
(The link was dead, latest archived version: https://web.archive.org/web/20161029174700/http://java.sys-con.com/node/1258827)
Sample code below will zip and password protect your file.
This REST service accepts bytes of the original file. It zips the byte array and password protects it. Then it sends bytes of password protected zipped file as response. The code is a sample of sending and receiving binary bytes to and from a REST service, and also of zipping a file with password protect. The bytes are zipped from stream, so no files are ever stored on the server.
Uses JAX-RS API using Jersey API in java
Client is using Jersey-client API.
Uses zip4j 1.3.2 open source library, and apache commons io.
#PUT
#Path("/bindata/protect/qparam")
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response zipFileUsingPassProtect(byte[] fileBytes, #QueryParam(value = "pass") String pass,
#QueryParam(value = "inputFileName") String inputFileName) {
System.out.println("====2001==== Entering zipFileUsingPassProtect");
System.out.println("fileBytes size = " + fileBytes.length);
System.out.println("password = " + pass);
System.out.println("inputFileName = " + inputFileName);
byte b[] = null;
try {
b = zipFileProtected(fileBytes, inputFileName, pass);
} catch (IOException e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
System.out.println(" ");
System.out.println("++++++++++++++++++++++++++++++++");
System.out.println(" ");
return Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; filename = " + inputFileName + ".zip").build();
}
private byte[] zipFileProtected(byte[] fileBytes, String fileName, String pass) throws IOException {
ByteArrayInputStream inputByteStream = null;
ByteArrayOutputStream outputByteStream = null;
net.lingala.zip4j.io.ZipOutputStream outputZipStream = null;
try {
//write the zip bytes to a byte array
outputByteStream = new ByteArrayOutputStream();
outputZipStream = new net.lingala.zip4j.io.ZipOutputStream(outputByteStream);
//input byte stream to read the input bytes
inputByteStream = new ByteArrayInputStream(fileBytes);
//init the zip parameters
ZipParameters zipParams = new ZipParameters();
zipParams.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParams.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParams.setEncryptFiles(true);
zipParams.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
zipParams.setPassword(pass);
zipParams.setSourceExternalStream(true);
zipParams.setFileNameInZip(fileName);
//create zip entry
outputZipStream.putNextEntry(new File(fileName), zipParams);
IOUtils.copy(inputByteStream, outputZipStream);
outputZipStream.closeEntry();
//finish up
outputZipStream.finish();
IOUtils.closeQuietly(inputByteStream);
IOUtils.closeQuietly(outputByteStream);
IOUtils.closeQuietly(outputZipStream);
return outputByteStream.toByteArray();
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inputByteStream);
IOUtils.closeQuietly(outputByteStream);
IOUtils.closeQuietly(outputZipStream);
}
return null;
}
Unit test below:
#Test
public void testPassProtectZip_with_params() {
byte[] inputBytes = null;
try {
inputBytes = FileUtils.readFileToByteArray(new File(inputFilePath));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("bytes read into array. size = " + inputBytes.length);
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080").path("filezip/services/zip/bindata/protect/qparam");
target = target.queryParam("pass", "mypass123");
target = target.queryParam("inputFileName", "any_name_here.pdf");
Invocation.Builder builder = target.request(MediaType.APPLICATION_OCTET_STREAM);
Response resp = builder.put(Entity.entity(inputBytes, MediaType.APPLICATION_OCTET_STREAM));
System.out.println("response = " + resp.getStatus());
Assert.assertEquals(Status.OK.getStatusCode(), resp.getStatus());
byte[] zipBytes = resp.readEntity(byte[].class);
try {
FileUtils.writeByteArrayToFile(new File(responseFilePathPasswordZipParam), zipBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
Feel free to use and modify. Please let me know if you find any errors. Hope this helps.
Edit 1 - Using QueryParam but you may use HeaderParam for PUT instead to hide passwd from plain sight. Modify the test method accordingly.
Edit 2 - REST path is filezip/services/zip/bindata/protect/qparam
filezip is name of war. services is the url mapping in web.xml. zip is class level path annotation. bindata/protect/qparam is the method level path annotation.
In new version of Zip4j, class Zip4jConstants was removed. Use EncryptionMethod and AesKeyStrength class instead. Documentation : https://github.com/srikanth-lingala/zip4j
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
List<File> filesToAdd = Arrays.asList(
new File("somefile"),
new File("someotherfile")
);
ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);
There is no default Java API to create a password protected file. There is another example about how to do it here.
Library Zip4J seems to be the preferred answer.
In case the privacy of the password is highly recommended, one might close a security gap in class ZipFile, which carries the password in plain text, even after the ZipFile is closed. Following method destroys the password.
public static void destroyZipPassword(ZipFile zip) throws DestroyFailedException
{
try
{
Field fdPwd = ZipFile.class.getDeclaredField("password");
fdPwd.setAccessible(true);
char[] password = (char[]) fdPwd.get(zip);
Arrays.fill(password, (char) 0);
}
catch (Exception e)
{
e.printStackTrace();
throw new DestroyFailedException(e.getMessage());
}
}

Categories