The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Create Zip File From Script

Hoang Dung
Tera Contributor

Hi everyone, I have a task to create an zip file include all attachment of record and attach to another record. I used code below to generate zip file but when download and extract it has error Invalid type. So anyone here know how to fix that. Thank you very much.

The code is:

 

var recordIds = ["ed92e8d173d023002728660c4cf6a7bc", "57af7aec73d423002728660c4cf6a71c"];
var tableName = "incident";
var fName = "TestAttachmentGenerateFromScript.zip";

try {
var outStream = new Packages.java.io.ByteArrayOutputStream();
var out = new Packages.java.util.zip.ZipOutputStream(outStream);

var queryStr = "table_name=incident^";
for (var i = 0; i < recordIds.length; i++) {
if (i < recordIds.length - 1) {
queryStr += "table_sys_id=" + recordIds[i] + "^OR";
} else {
queryStr += "table_sys_id=" + recordIds[i];
}
}

var attachmentGr = new GlideRecord("sys_attachment");
attachmentGr.addEncodedQuery(queryStr);
attachmentGr.query();
while (attachmentGr.next()) {
var sa = new GlideSysAttachmentInputStream(attachmentGr.getValue("sys_id"));
sa.writeTo(outStream, 0, 0);

var gsa = new GlideSysAttachment();
var fileStream = gsa.getBytes(attachmentGr);

gs.info("File stream: " + fileStream);
var fileName = attachmentGr.getValue("file_name");

out.putNextEntry(new Packages.java.util.zip.ZipEntry(fileName));
out.write(fileStream, 0, fileStream.length);
out.closeEntry();
}

outStream.close();
out.close();

//gs.info(GlideStringUtil.base64Encode(outStream));
var incGr = new GlideRecord("incident");
if (incGr.get("a623cdb073a023002728660c4cf6a768")) {
var stringUtil = new GlideStringUtil();

gs.info(outStream.toByteArray());
//gs.info("OutStream: " + stringUtil.base64Encode(outStream));
var attachment = new GlideSysAttachment();
attachment.write(incGr, fName, "application/zip", stringUtil.base64Encode(outStream.toByteArray()));
}
} catch (ex) {
gs.info("--> Error when zip file: " + ex);
}

 

 

 
1 ACCEPTED SOLUTION

Siddhesh Jadhav
Kilo Sage

Hello @Hoang Dung,

 

It looks like you're facing an issue while generating the ZIP file, likely due to how the attachment stream is being processed and written to the ZIP. Here’s an improved version of your script that addresses potential issues with stream handling and encoding:

 

var recordIds = ["ed92e8d173d023002728660c4cf6a7bc", "57af7aec73d423002728660c4cf6a71c"];
var tableName = "incident";
var fName = "TestAttachmentGenerateFromScript.zip";

try {
    // Create a byte output stream for the zip file
    var outStream = new Packages.java.io.ByteArrayOutputStream();
    var out = new Packages.java.util.zip.ZipOutputStream(outStream);

    // Loop through each record ID to fetch attachments
    for (var i = 0; i < recordIds.length; i++) {
        var attachmentGr = new GlideRecord("sys_attachment");
        attachmentGr.addQuery("table_name", tableName);
        attachmentGr.addQuery("table_sys_id", recordIds[i]);
        attachmentGr.query();

        while (attachmentGr.next()) {
            // Get the file stream from the attachment
            var gsa = new GlideSysAttachment();
            var fileStream = gsa.getBytes(attachmentGr);
            var fileName = attachmentGr.getValue("file_name");

            // Add the attachment as an entry in the zip file
            out.putNextEntry(new Packages.java.util.zip.ZipEntry(fileName));
            out.write(fileStream, 0, fileStream.length);
            out.closeEntry();
        }
    }

    // Close the streams
    out.close();
    outStream.close();

    // Attach the zip file to another record
    var incGr = new GlideRecord("incident");
    if (incGr.get("a623cdb073a023002728660c4cf6a768")) {
        var attachment = new GlideSysAttachment();
        attachment.write(incGr, fName, "application/zip", outStream.toByteArray());
    }
} catch (ex) {
    gs.error("Error when zipping file: " + ex);
}


Changes made:
1. Stream Writing: Made sure to retrieve and correctly write each attachment as bytes before adding it to the ZIP stream.
2. GlideSysAttachment.getBytes(): Used the appropriate `getBytes` method to handle binary data from attachments.
3. Stream Closure: Correctly closed streams to avoid any stream corruption.
4. Error Handling: Improved logging for easier troubleshooting.

This script should fix your issue with ZIP extraction.

 

Thanks & Regards,

Siddhesh Jadhav

 

If this solution helps, please mark it as helpful and accepted.

 

View solution in original post

4 REPLIES 4

Siddhesh Jadhav
Kilo Sage

Hello @Hoang Dung,

 

It looks like you're facing an issue while generating the ZIP file, likely due to how the attachment stream is being processed and written to the ZIP. Here’s an improved version of your script that addresses potential issues with stream handling and encoding:

 

var recordIds = ["ed92e8d173d023002728660c4cf6a7bc", "57af7aec73d423002728660c4cf6a71c"];
var tableName = "incident";
var fName = "TestAttachmentGenerateFromScript.zip";

try {
    // Create a byte output stream for the zip file
    var outStream = new Packages.java.io.ByteArrayOutputStream();
    var out = new Packages.java.util.zip.ZipOutputStream(outStream);

    // Loop through each record ID to fetch attachments
    for (var i = 0; i < recordIds.length; i++) {
        var attachmentGr = new GlideRecord("sys_attachment");
        attachmentGr.addQuery("table_name", tableName);
        attachmentGr.addQuery("table_sys_id", recordIds[i]);
        attachmentGr.query();

        while (attachmentGr.next()) {
            // Get the file stream from the attachment
            var gsa = new GlideSysAttachment();
            var fileStream = gsa.getBytes(attachmentGr);
            var fileName = attachmentGr.getValue("file_name");

            // Add the attachment as an entry in the zip file
            out.putNextEntry(new Packages.java.util.zip.ZipEntry(fileName));
            out.write(fileStream, 0, fileStream.length);
            out.closeEntry();
        }
    }

    // Close the streams
    out.close();
    outStream.close();

    // Attach the zip file to another record
    var incGr = new GlideRecord("incident");
    if (incGr.get("a623cdb073a023002728660c4cf6a768")) {
        var attachment = new GlideSysAttachment();
        attachment.write(incGr, fName, "application/zip", outStream.toByteArray());
    }
} catch (ex) {
    gs.error("Error when zipping file: " + ex);
}


Changes made:
1. Stream Writing: Made sure to retrieve and correctly write each attachment as bytes before adding it to the ZIP stream.
2. GlideSysAttachment.getBytes(): Used the appropriate `getBytes` method to handle binary data from attachments.
3. Stream Closure: Correctly closed streams to avoid any stream corruption.
4. Error Handling: Improved logging for easier troubleshooting.

This script should fix your issue with ZIP extraction.

 

Thanks & Regards,

Siddhesh Jadhav

 

If this solution helps, please mark it as helpful and accepted.

 

thanks, it's worked 😁

hamanthk
Tera Contributor

Hi @Hoang Dung @Siddhesh Jadhav 

Need your help.  I am trying to perform a similar process with the below code

 

        var output = new Packages.java.io.ByteArrayOutputStream();
        var gzip = new Packages.java.util.zip.GZIPOutputStream(output);
        gzip.write(objSarif);
        gzip.close();
        gs.info(Packages.org.apache.commons.codec.binary.Base64.encodeBase64String(output.toByteArray()));
 

and when I execute the code I am receiving security restriction error

Security restricted: Attempted access to restricted class name java.util.zip.GZIPOutputStream.

Have you faced this error and if so please let me know what needs to be done.

Hi @hamanthk @Hoang Dung @Siddhesh Jadhav 

any solution for java error?

my script is defined in global scope still java error am facing 

Generation failed: {"error":"ZIP failed","details":{"error":"ZIP creation failed","details":"\"java\" is not defined."}}