Example usage for org.apache.commons.lang SerializationUtils serialize

List of usage examples for org.apache.commons.lang SerializationUtils serialize

Introduction

In this page you can find the example usage for org.apache.commons.lang SerializationUtils serialize.

Prototype

public static void serialize(Serializable obj, OutputStream outputStream) 

Source Link

Document

Serializes an Object to the specified stream.

The stream will be closed once the object is written.

Usage

From source file:SerializationUtilsTrial.java

public static void main(String[] args) {
    try {// ww w .j a v  a 2  s.  co m
        // File to serialize object to
        String fileName = "testSerialization.ser";

        // New file output stream for the file
        FileOutputStream fos = new FileOutputStream(fileName);

        // Serialize String
        SerializationUtils.serialize("SERIALIZE THIS", fos);
        fos.close();

        // Open FileInputStream to the file
        FileInputStream fis = new FileInputStream(fileName);

        // Deserialize and cast into String
        String ser = (String) SerializationUtils.deserialize(fis);
        System.out.println(ser);
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.cosmocode.palava.cache.keysets.MemoryKeySet.java

@Override
public void dispose() throws LifecycleException {
    // write list to hard disk
    try {// w w  w  . jav  a2 s .com
        SerializationUtils.serialize(Serializable.class.cast(keys),
                Files.newOutputStreamSupplier(getSerializationFile()).getOutput());
    } catch (IOException e) {
        throw new LifecycleException(e);
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.analyze.DetectedByAssertAnalyzer.java

@Override
public String analyze(Iterable<Mutation> mutations, HtmlReport report) {
    HashMultimap<String, Long> mutationPerAssert = HashMultimap.create();
    int totalMutations = 0;
    for (Mutation m : mutations) {
        totalMutations++;//from   w  ww.  j a  v  a 2 s .c  o m
        MutationTestResult mutationResult = m.getMutationResult();
        mutationPerAssert.put("non.existing.location-1", m.getId());
        if (mutationResult != null) {
            Collection<TestMessage> failures = mutationResult.getFailures();
            boolean foundByAssert = false;
            for (TestMessage tm : failures) {
                String message = tm.getMessage();
                List<Location> locations = parseLocation(message);
                for (Location loc : locations) {
                    if (loc == null) {
                        logger.warn("No location found for failing test " + tm);
                    } else {
                        mutationPerAssert.put(loc.toString(), m.getId());
                        foundByAssert = true;
                    }
                }
            }
            if (!foundByAssert && m.isDetected()) {
                mutationPerAssert.put("implicit", m.getId());
            }
        }

    }
    String message = "Assert locations: " + mutationPerAssert.keySet().size();
    message += "\nTotal mappings: " + mutationPerAssert.size();
    message += "\nTotal mutations: " + totalMutations;
    try {
        SerializationUtils.serialize(mutationPerAssert,
                new FileOutputStream(new File("mutationPerAssert.ser")));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    return message;
}

From source file:com.ephesoft.dcma.batch.dao.impl.BatchClassWorkflowDetailDaoImpl.java

@Override
public void createBatchClassWorkflow(final WorkflowDetailContainer batchClassWorkflowContainer) {
    String batchClassIdentifier = batchClassWorkflowContainer.getBatchIdentifier();
    String baseFolderLocation = batchSchemaService.getBaseFolderLocation();
    String serilaizedFileName = EphesoftStringUtil.concatenate(baseFolderLocation, File.separator,
            batchClassIdentifier, File.separator, batchClassIdentifier, ICommonConstants.UNDERSCORE,
            BatchConstants.WORKFLOWS_CONSTANT);
    LOGGER.debug("Serialized file name is: ", serilaizedFileName);
    File serializedFile = new File(
            EphesoftStringUtil.concatenate(serilaizedFileName, FileType.SER.getExtensionWithDot()));
    FileOutputStream fileOutputStream = null;

    // Changed to make deletion of only serialised file containing batch class workflows.
    if (serializedFile.exists()) {
        serializedFile.delete();/*from  ww w .ja v  a  2s .c  om*/
    }
    try {
        fileOutputStream = new FileOutputStream(serializedFile);
        BufferedOutputStream bufferedOutputstream = new BufferedOutputStream(fileOutputStream);
        SerializationUtils.serialize(batchClassWorkflowContainer, bufferedOutputstream);
    } catch (FileNotFoundException fileNotFoundException) {
        LOGGER.error(fileNotFoundException,
                "Serialized file just created for workflows does not exist. Error during serializing the properties for Batch class: ",
                batchClassIdentifier);
    } catch (Exception exception) {
        LOGGER.error(exception, "Error during serializing the properties for Batch class: ",
                batchClassIdentifier);
    } finally {
        try {
            if (null != fileOutputStream) {
                fileOutputStream.close();
            }
        } catch (IOException ioException) {
            LOGGER.error(ioException, "Problem closing stream for file: ", serializedFile.getName());
        }
    }
}

From source file:com.ephesoft.dcma.batch.dao.BatchPropertiesDao.java

/**
 * Method to create serialised file for Batch class properties.
 * //w  ww  . j a v  a2s.  com
 * @param batchClassIdentifier batch class identifier corresponding to which serialised file is to be created.
 * @return Returns the {@link BatchPluginPropertyContainer} instance.
 */
public BatchPluginPropertyContainer createBatchPropertiesFile(String batchClassIdentifier) {
    String baseFolderLocation = batchSchemaService.getBaseFolderLocation();
    File serializedFile = new File(EphesoftStringUtil.concatenate(baseFolderLocation, File.separator,
            batchClassIdentifier, File.separator, batchClassIdentifier, BatchConstants.DOT, EXTN));
    BatchPluginPropertyContainer container = null;
    List<BatchClassPluginConfig> batchClassPluginConfigs = batchClassPluginConfigDao
            .getAllPluginPropertiesForBatchClass(batchClassIdentifier);

    // to lazily load KVPageProcess objects
    for (BatchClassPluginConfig batchClassPluginConfig : batchClassPluginConfigs) {
        for (KVPageProcess eachKvPageProcess : batchClassPluginConfig.getKvPageProcesses()) {
            if (log.isDebugEnabled() && eachKvPageProcess != null) {
                log.debug(eachKvPageProcess.getKeyPattern());
            }
        }
    }

    List<BatchClassDynamicPluginConfig> batchClassDynamicPluginConfigs = batchClassDynamicPluginConfigDao
            .getAllDynamicPluginPropertiesForBatchClass(batchClassIdentifier);
    container = new BatchPluginPropertyContainer(String.valueOf(batchClassIdentifier));
    container.populate(batchClassPluginConfigs);
    container.populateDynamicPluginConfigs(batchClassDynamicPluginConfigs);
    List<DocumentType> documentTypes = documentTypeService
            .getDocTypeByBatchClassIdentifier(batchClassIdentifier);
    container.populateDocumentTypes(documentTypes, batchClassIdentifier);
    FileOutputStream fileOutputStream = null;

    // Changed to make deletion of only serialised file containing batch class data.
    if (serializedFile.exists()) {
        serializedFile.delete();
    }
    try {
        fileOutputStream = new FileOutputStream(serializedFile);
        SerializationUtils.serialize(container, fileOutputStream);

    } catch (Exception e) {
        log.error("Error during serializing the properties for Batch class: " + batchClassIdentifier, e);
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            log.error("Problem closing stream for file :" + serializedFile.getName(), e);
        }
    }

    return container;
}

From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER));
    String exportLearning = req.getParameter(EXPORT_LEARNING);
    if (batchClass == null) {
        log.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {//from   w w w  . j  av a2s  . c  o  m
        // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file.
        batchClass.setAdvancedBatchClass(Boolean.TRUE);
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyConnections(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);
        BatchClassUtil.exportCMISConfiguration(batchClass);
        // BatchClassUtil.decryptAllPasswords(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);
        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                String[] folderList = originalFolder.list();
                Arrays.sort(folderList);

                for (int i = 0; i < folderList.length; i++) {
                    if (folderList[i].endsWith(SERIALIZATION_EXT)) {
                        // skip previous ser file since new is created.
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getTestTableFolderName())
                            || FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                                    batchSchemaService.getFileboundPluginMappingFolderName())) {
                        // Skip this folder
                        continue;
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                            batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (!(FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:com.ephesoft.gxt.admin.server.ExportIndexFieldDownloadServlet.java

/**
 * This API is used to process document types to export.
 * //  www .  j a  v a  2  s . com
 * @param fieldTypeList {@link List<{@link FieldType}>} document type list to export.
 * @param documentType {@link documentType} batch class for which document type is exporting.
 * @param bsService {@link BatchSchemaService}.
 * @param isImagemagickFd boolean to identify whether image classification samples to export.
 * @param isSearchSampleFd boolean to identify whether search classification samples to export.
 * @param resp {@link HttpServletResponse}
 * @return
 */
private void processExportFieldTypes(final List<FieldType> fieldTypeList, final BatchSchemaService bsService,
        final HttpServletResponse resp, String zipFileName) throws IOException {
    final String exportSerFdPath = bsService.getBatchExportFolderLocation();

    final String parentFdPath = exportSerFdPath + File.separator + zipFileName;

    for (int docNum = 0; docNum < fieldTypeList.size(); docNum++) {
        FieldType fieldType = null;
        fieldType = fieldTypeList.get(docNum);
        createDirectory(parentFdPath);
        fieldType = modifyFieldTypeForExport(fieldType);

        final File serializedFile = new File(
                parentFdPath + File.separator + fieldType.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(fieldType, new FileOutputStream(serializedFile));

        } catch (final FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (final IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }

    }
}

From source file:com.ephesoft.gxt.systemconfig.server.ExportRegexPoolServlet.java

/**
 * Overridden doGet method.//from  www  .  j a va2s  . c  o  m
 */
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    final RegexGroupService regexGroupService = this.getSingleBeanOfType(RegexGroupService.class);
    final List<RegexGroup> regexGroupList = regexGroupService.getRegexGroups();

    if (regexGroupList == null) {
        LOGGER.error("Regex group list is null.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Regex group list is null.");
    } else {
        try {
            final Calendar cal = Calendar.getInstance();
            final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

            final SimpleDateFormat formatter = new SimpleDateFormat(CoreCommonConstant.DATE_FORMAT);
            final String formattedDate = formatter.format(new Date());
            final String zipFileName = StringUtil.concatenate(SystemConfigConstants.REGEX_POOL,
                    CoreCommonConstant.UNDERSCORE, formattedDate, CoreCommonConstant.UNDERSCORE,
                    cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.SECOND));
            final String tempFolderLocation = StringUtil.concatenate(exportSerailizationFolderPath,
                    File.separator, zipFileName);
            final File copiedFolder = new File(tempFolderLocation);

            if (copiedFolder.exists()) {
                copiedFolder.delete();
            }

            // Setting the parent of regex pattern list to null for exporting
            RegexUtil.exportRegexPatterns(regexGroupList);

            // Setting the id of regex group list to "0" for exporting
            for (final RegexGroup regexGroup : regexGroupList) {
                regexGroup.setId(0);
            }
            copiedFolder.mkdirs();

            final File serializedExportFile = new File(tempFolderLocation + File.separator
                    + SystemConfigConstants.REGEX_POOL + SystemConfigConstants.SERIALIZATION_EXT);

            try {
                SerializationUtils.serialize((Serializable) regexGroupList,
                        new FileOutputStream(serializedExportFile));
                final File originalFolder = new File(
                        StringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator,
                                SystemConfigConstants.REGEX_POOL));

                if (originalFolder.isDirectory()) {
                    final String[] folderList = originalFolder.list();
                    Arrays.sort(folderList);
                }
            } catch (final FileNotFoundException fileNotFoundException) {
                // Unable to read serializable file
                LOGGER.error("Error occurred while creating the serializable file." + fileNotFoundException,
                        fileNotFoundException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error occurred while creating the serializable file.");
            }

            resp.setContentType(SystemConfigConstants.APPLICATION_X_ZIP);
            resp.setHeader(SystemConfigConstants.CONTENT_DISPOSITION,
                    StringUtil.concatenate(SystemConfigConstants.ATTACHMENT_FILENAME, zipFileName,
                            SystemConfigConstants.ZIP_EXT, SystemConfigConstants.HEADER_MODE));
            ServletOutputStream out = null;
            ZipOutputStream zipOutput = null;
            try {
                out = resp.getOutputStream();
                zipOutput = new ZipOutputStream(out);
                FileUtils.zipDirectory(tempFolderLocation, zipOutput, zipFileName);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (final IOException ioException) {
                // Unable to create the temporary export file(s)/folder(s)
                LOGGER.error("Error occurred while creating the zip file." + ioException, ioException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unable to export.Please try again.");
            } finally {
                // clean up code
                if (zipOutput != null) {
                    zipOutput.close();
                }
                if (out != null) {
                    out.flush();
                }
                FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
            }
        } catch (final Exception exception) {
            LOGGER.error("ERROR IN EXPORT:  " + exception, exception);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        }
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ExportBatchClassDownloadServlet.java

/**
 * Overriden doGet method.//from  w ww  .j  a  v a2  s  .  c o  m
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter("identifier"));
    if (batchClass == null) {
        LOG.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy", Locale.getDefault());
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + BatchClassManagementConstants.UNDERSCORE
                + formattedDate + BatchClassManagementConstants.UNDERSCORE + cal.get(Calendar.HOUR_OF_DAY)
                + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));
            boolean isImagemagickBaseFolder = false;
            String imageMagickBaseFolderParam = req
                    .getParameter(batchSchemaService.getImagemagickBaseFolderName());
            if (imageMagickBaseFolderParam != null && (imageMagickBaseFolderParam
                    .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                    || Boolean.parseBoolean(imageMagickBaseFolderParam))) {
                isImagemagickBaseFolder = true;
            }

            boolean isSearchSampleName = false;
            String isSearchSampleNameParam = req.getParameter(batchSchemaService.getSearchSampleName());
            if (isSearchSampleNameParam != null
                    && (isSearchSampleNameParam.equalsIgnoreCase(batchSchemaService.getSearchSampleName())
                            || Boolean.parseBoolean(isSearchSampleNameParam))) {
                isSearchSampleName = true;
            }

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                validateFolderAndFile(batchSchemaService, copiedFolder, isImagemagickBaseFolder,
                        isSearchSampleName, originalFolder);
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:com.ephesoft.gxt.admin.server.ExportDocumentTypeDownloadServlet.java

/**
 * This API is used to process document types to export.
 * //from   w  w w  .  j  a v  a2s.co m
 * @param docTypeList {@link List<{@link DocumentType}>} document type list to export.
 * @param batchClass {@link BatchClass} batch class for which document type is exporting.
 * @param bsService {@link BatchSchemaService}.
 * @param isImagemagickFd boolean to identify whether image classification samples to export.
 * @param isSearchSampleFd boolean to identify whether search classification samples to export.
 * @param resp {@link HttpServletResponse}
 * @return
 */
private void processDocumentTypes(final List<DocumentType> docTypeList, final BatchClass batchClass,
        final BatchSchemaService bsService, final boolean isImagemagickFd, final boolean isSearchSampleFd,
        final HttpServletResponse resp) throws IOException {
    String[] imageMagickFdList = null;
    String[] searchFdList = null;
    final String imageMagickFdPath = bsService.getBaseSampleFDLock() + File.separator
            + batchClass.getIdentifier() + File.separator + bsService.getImagemagickBaseFolderName();
    final String searchFdPath = bsService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier()
            + File.separator + bsService.getSearchSampleName();
    imageMagickFdList = getSubDirectoriesList(imageMagickFdPath);
    searchFdList = getSubDirectoriesList(searchFdPath);
    final String exportSerFdPath = bsService.getBatchExportFolderLocation();

    final String zipFileName = batchClass.getIdentifier() + "_" + "DocumentTypes";
    final String parentFdPath = exportSerFdPath + File.separator + zipFileName;

    for (int docNum = 0; docNum < docTypeList.size(); docNum++) {
        DocumentType documentType = null;
        documentType = docTypeList.get(docNum);
        final Calendar cal = Calendar.getInstance();

        final SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        final String formattedDate = formatter.format(new Date());
        final String documentFolderName = documentType.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);
        final String tempFdLoc = parentFdPath + File.separator + documentFolderName;
        createDirectory(tempFdLoc);

        documentType = modifyDocumentTypeToExport(documentType);

        final File serializedFile = new File(
                tempFdLoc + File.separator + documentType.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(documentType, new FileOutputStream(serializedFile));

            if (isImagemagickFd) {
                final String imFdPath = parentFdPath + File.separator + documentFolderName + File.separator
                        + bsService.getImagemagickBaseFolderName();
                copyDocumentType(imageMagickFdList, documentType, imageMagickFdPath, imFdPath);
            }

            if (isSearchSampleFd) {
                final String ssFolderPath = parentFdPath + File.separator + documentFolderName + File.separator
                        + bsService.getSearchSampleName();
                copyDocumentType(searchFdList, documentType, searchFdPath, ssFolderPath);
            }

        } catch (final FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (final IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }

    }
}