Example usage for java.nio.channels FileChannel transferTo

List of usage examples for java.nio.channels FileChannel transferTo

Introduction

In this page you can find the example usage for java.nio.channels FileChannel transferTo.

Prototype

public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;

Source Link

Document

Transfers bytes from this channel's file to the given writable byte channel.

Usage

From source file:edu.harvard.iq.dvn.ingest.dsb.DSBWrapper.java

public String ingest(StudyFileEditBean file) throws IOException {
    dbgLog.fine("***** DSBWrapper: ingest(): start *****\n");

    String ddi = null;/*from   ww w  . j a va2  s.  c  o m*/

    BufferedInputStream infile = null;

    // ingest-source file
    File tempFile = new File(file.getTempSystemFileLocation());
    SDIOData sd = null;

    if (file.getControlCardSystemFileLocation() == null) {
        // A "classic", 1 file ingest:        

        String mime_type = file.getStudyFile().getFileType();

        infile = new BufferedInputStream(new FileInputStream(tempFile));

        dbgLog.info("\nfile mimeType=" + mime_type + "\n\n");

        // get available FileReaders for this MIME-type
        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByMIMEType(mime_type);

        if (itr.hasNext()) {
            // use the first Subsettable data reader
            StatDataFileReader sdioReader = itr.next();

            dbgLog.info("reader class name=" + sdioReader.getClass().getName());

            if (mime_type != null) {
                String requestedCharacterEncoding = file.getDataLanguageEncoding();
                if (requestedCharacterEncoding != null) {
                    dbgLog.fine("Will try to process the file assuming that the character strings are "
                            + "encoded in " + requestedCharacterEncoding);
                    sdioReader.setDataLanguageEncoding(requestedCharacterEncoding);
                }
                sd = sdioReader.read(infile, null);
            } else {
                // fail-safe block if mime_type is null
                // check the format type again and then read the file
                dbgLog.info("mime-type was null: use the back-up method");
                sd = StatDataIO.read(infile, null);
            }
        } else {

            throw new IllegalArgumentException(
                    "No FileReader Class found" + " for this mime type=" + mime_type);
        }
    } else {
        // This is a 2-file ingest.
        // As of now, there are 2 supported methods: 
        // 1. CSV raw data file + SPSS control card;
        // 2. TAB raw data file + DDI control card;
        // NOTE, that "POR file with the Extended Labels" is NOT a 2-file.
        // control card-based ingest! Rather, we ingest the file as a regular
        // SPSS/POR dataset, then modify the variable labels in the resulting
        // TabularFile. 

        File rawDataFile = tempFile;

        infile = new BufferedInputStream(new FileInputStream(file.getControlCardSystemFileLocation()));

        String controlCardType = file.getControlCardType();

        if (controlCardType == null || controlCardType.equals("")) {
            dbgLog.info("No Control Card Type supplied.");

            throw new IllegalArgumentException("No Control Card Type supplied.");
        }

        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByFormatName(controlCardType);

        if (!itr.hasNext()) {
            dbgLog.info("No FileReader class found for " + controlCardType + ".");

            throw new IllegalArgumentException("No FileReader Class found for " + controlCardType + ".");
        }

        StatDataFileReader sdioReader = itr.next();

        dbgLog.info("reader class name=" + sdioReader.getClass().getName());

        sd = sdioReader.read(infile, rawDataFile);

    }

    if (sd != null) {
        SDIOMetadata smd = sd.getMetadata();

        // tab-file: source file
        String tabDelimitedDataFileLocation = smd.getFileInformation().get("tabDelimitedDataFileLocation")
                .toString();

        dbgLog.fine("tabDelimitedDataFileLocation=" + tabDelimitedDataFileLocation);

        dbgLog.fine("data file(tempFile): abs path:\n" + file.getTempSystemFileLocation());
        dbgLog.fine("mimeType :\n" + file.getStudyFile().getFileType());

        if (infile != null) {
            infile.close();
        }

        // parse the response
        StudyFile f = file.getStudyFile();

        // first, check dir
        // create a sub-directory "ingested"
        File newDir = new File(tempFile.getParentFile(), "ingested");

        if (!newDir.exists()) {
            newDir.mkdirs();
        }
        dbgLog.fine("newDir: abs path:\n" + newDir.getAbsolutePath());

        // tab-file case: destination
        File newFile = new File(newDir, tempFile.getName());

        // nio-based file-copying idiom
        FileInputStream fis = new FileInputStream(tabDelimitedDataFileLocation);
        FileOutputStream fos = new FileOutputStream(newFile);
        FileChannel fcin = fis.getChannel();
        FileChannel fcout = fos.getChannel();
        fcin.transferTo(0, fcin.size(), fcout);
        fcin.close();
        fcout.close();
        fis.close();
        fos.close();

        dbgLog.fine("newFile: abs path:\n" + newFile.getAbsolutePath());

        // store the tab-file location
        file.setIngestedSystemFileLocation(newFile.getAbsolutePath());

        // finally, if we have an extended variable map, let's replace the 
        // labels that have been found in the data file: 

        if (file.getExtendedVariableLabelMap() != null) {
            for (String varName : file.getExtendedVariableLabelMap().keySet()) {
                if (smd.getVariableLabel().containsKey(varName)) {
                    smd.getVariableLabel().put(varName, file.getExtendedVariableLabelMap().get(varName));
                }
            }
        }

        // return xmlToParse;
        DDIWriter dw = new DDIWriter(smd);
        ddi = dw.generateDDI();

        return ddi;
    }
    return null;
}

From source file:org.t3.metamediamanager.MediaCenterDataMediaBrowser.java

/**
 * use for copy images given in an array in a folder given in parameters
 * @param images//  w ww .j  av a 2 s.  c om
 * @param newFileName
 */
public void copy_images(String images, String newFileName) {

    FileChannel in = null; // canal d'entre
    FileChannel out = null; // canal de sortie
    try {
        // Init
        in = new FileInputStream(images).getChannel();
        out = new FileOutputStream(newFileName).getChannel();

        // Copy in->out
        in.transferTo(0, in.size(), out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void copyObject(String sourceBucket, String sourceObject, String destinationBucket,
        String destinationObject) throws IOException {
    File oldObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + sourceBucket + FILE_SEPARATOR + sourceObject);
    File newObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + destinationBucket + FILE_SEPARATOR + destinationObject);
    if (!oldObjectFile.equals(newObjectFile)) {
        FileInputStream fileInputStream = null;
        FileChannel fileIn = null;
        FileOutputStream fileOutputStream = null;
        FileChannel fileOut = null;
        try {/*from  ww w . j a  va 2  s . com*/
            fileInputStream = new FileInputStream(oldObjectFile);
            fileIn = fileInputStream.getChannel();
            fileOutputStream = new FileOutputStream(newObjectFile);
            fileOut = fileOutputStream.getChannel();
            fileIn.transferTo(0, fileIn.size(), fileOut);
        } finally {
            if (fileIn != null)
                fileIn.close();
            if (fileInputStream != null)
                fileInputStream.close();
            if (fileOut != null)
                fileOut.close();
            if (fileOutputStream != null)
                fileOutputStream.close();
        }
    }
}

From source file:com.stimulus.archiva.store.MessageStore.java

public void copyEmail(File source, File dest) throws MessageStoreException {

    logger.debug("copyEmail()");
    FileChannel in = null, out = null;

    try {/*  w  w  w .j  a  va  2  s. com*/

        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(dest).getChannel();
        in.transferTo(0, in.size(), out);

    } catch (Exception e) {
        throw new MessageStoreException("failed to copy email {src='" + source + "=',dest='" + dest + "'", e,
                logger);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        ;
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
            }
        ;
    }
}

From source file:com.stfalcon.contentmanager.ContentManager.java

private void handleMediaContent(final Intent data) {
    pickContentListener.onStartContentLoading();

    new Thread(new Runnable() {
        public void run() {
            try {
                Uri contentVideoUri = data.getData();
                FileInputStream in = (FileInputStream) activity.getContentResolver()
                        .openInputStream(contentVideoUri);
                if (targetFile == null) {
                    targetFile = createFile(savedContent);
                }//from  www  . ja  v a2 s. co  m
                FileOutputStream out = new FileOutputStream(targetFile);
                FileChannel inChannel = in.getChannel();
                FileChannel outChannel = out.getChannel();
                inChannel.transferTo(0, inChannel.size(), outChannel);

                in.close();
                out.close();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pickContentListener.onContentLoaded(Uri.fromFile(targetFile), savedContent.toString());
                    }
                });
            } catch (final Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pickContentListener.onError(e.getMessage());
                    }
                });
            }
        }
    }).start();
}

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Moved this code into it's own method so moveTo could use it when the move is across file systems
 *///  w  ww . j  a v  a2  s.  c  o  m
private void copyAction(File srcFile, File destFile) throws FileNotFoundException, IOException {
    FileInputStream istream = new FileInputStream(srcFile);
    FileOutputStream ostream = new FileOutputStream(destFile);
    FileChannel input = istream.getChannel();
    FileChannel output = ostream.getChannel();

    try {
        input.transferTo(0, input.size(), output);
    } finally {
        istream.close();
        ostream.close();
        input.close();
        output.close();
    }
}

From source file:com.MustacheMonitor.MustacheMonitor.FileUtils.java

/**
 * Copy a file/* www .j  a v a  2  s. c  o  m*/
 *
 * @param srcFile file to be copied
 * @param destFile destination to be copied to
 * @return a FileEntry object
 * @throws IOException
 * @throws InvalidModificationException
 * @throws JSONException
 */
private JSONObject copyFile(File srcFile, File destFile)
        throws IOException, InvalidModificationException, JSONException {
    // Renaming a file to an existing directory should fail
    if (destFile.exists() && destFile.isDirectory()) {
        throw new InvalidModificationException("Can't rename a file to a directory");
    }

    FileChannel input = new FileInputStream(srcFile).getChannel();
    FileChannel output = new FileOutputStream(destFile).getChannel();

    input.transferTo(0, input.size(), output);

    input.close();
    output.close();

    /*
    if (srcFile.length() != destFile.length()) {
    return false;
    }
    */

    return getEntry(destFile);
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

private void copyJarsAsBundles(final List<Bundle> bundles, final String copyJarsAsBundlesTo) {

    final File dir = new File(copyJarsAsBundlesTo);
    if (dir.exists()) {
        if (!dir.isDirectory()) {
            log.error(dir.getAbsolutePath() + " is not a directory.");
            return;
        }//from  w w w  .ja  va 2s .c o  m
    } else {
        dir.mkdirs();
    }

    log.info("Copying " + bundles.size() + " bundles into: " + dir.getAbsolutePath());

    for (final Bundle bundle : bundles) {
        final File target = new File(dir, bundle.getSymbolicName() + "_" + bundle.getVersion() + ".jar");

        FileChannel in = null;
        FileChannel out = null;

        try {
            in = new FileInputStream(bundle.getJarLocation()).getChannel();
            out = new FileOutputStream(target).getChannel();

            // According to
            // http://www.rgagnon.com/javadetails/java-0064.html
            // we cannot copy files greater than 64 MB.
            // magic number for Windows, 64Mb - 32Kb)
            final int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            final long size = in.size();
            long position = 0;
            while (position < size) {
                position += in.transferTo(position, maxCount, out);
            }

        } catch (final IOException e) {
            log.error("Error whily copying '" + bundle.getJarLocation().getAbsolutePath() + "' to '"
                    + target.getAbsolutePath() + "'", e);
            return;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (final IOException e) {
                throw new RuntimeException("Could not recover from error.", e);
            }
        }
    }
}

From source file:fr.paris.lutece.plugins.directory.web.action.ExportDirectoryAction.java

/**
 * {@inheritDoc}//w w  w . j a  v  a  2  s.  c  om
 */
@Override
public IPluginActionResult process(HttpServletRequest request, HttpServletResponse response,
        AdminUser adminUser, DirectoryAdminSearchFields searchFields) throws AccessDeniedException {
    DefaultPluginActionResult result = new DefaultPluginActionResult();

    String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY);
    int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory);
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin());
    String strIdDirectoryXsl = request.getParameter(PARAMETER_ID_DIRECTORY_XSL);
    int nIdDirectoryXsl = DirectoryUtils.convertStringToInt(strIdDirectoryXsl);
    WorkflowService workflowService = WorkflowService.getInstance();
    boolean bWorkflowServiceEnable = workflowService.isAvailable();
    String strShotExportFinalOutPut = null;
    DirectoryXsl directoryXsl = DirectoryXslHome.findByPrimaryKey(nIdDirectoryXsl, getPlugin());

    // -----------------------------------------------------------------------
    if ((directory == null) || (directoryXsl == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE,
            strIdDirectory, DirectoryResourceIdService.PERMISSION_MANAGE_RECORD, adminUser)) {
        throw new AccessDeniedException(
                I18nService.getLocalizedString(MESSAGE_ACCESS_DENIED, request.getLocale()));
    }

    String strFileExtension = directoryXsl.getExtension();
    String strFileName = directory.getTitle() + "." + strFileExtension;
    strFileName = UploadUtil.cleanFileName(strFileName);

    boolean bIsCsvExport = strFileExtension.equals(EXPORT_CSV_EXT);
    boolean bDisplayDateCreation = directory.isDateShownInExport();
    boolean bDisplayDateModification = directory.isDateModificationShownInExport();

    List<Integer> listResultRecordId = new ArrayList<Integer>();

    if (request.getParameter(PARAMETER_BUTTON_EXPORT_SEARCH) != null) {
        String[] selectedRecords = request.getParameterValues(PARAMETER_SELECTED_RECORD);
        List<String> listSelectedRecords;

        if (selectedRecords != null) {
            listSelectedRecords = Arrays.asList(selectedRecords);

            if ((listSelectedRecords != null) && (listSelectedRecords.size() > 0)) {
                for (String strRecordId : listSelectedRecords) {
                    listResultRecordId.add(Integer.parseInt(strRecordId));
                }
            }
        } else {
            // sort order and sort entry are not needed in export
            listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, true,
                    null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale());
        }
    } else {
        // sort order and sort entry are not needed in export
        listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, false,
                null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale());
    }

    EntryFilter entryFilter = new EntryFilter();
    entryFilter.setIdDirectory(directory.getIdDirectory());
    entryFilter.setIsGroup(EntryFilter.FILTER_FALSE);
    entryFilter.setIsComment(EntryFilter.FILTER_FALSE);
    entryFilter.setIsShownInExport(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntryResultSearch = EntryHome.getEntryList(entryFilter, getPlugin());

    Map<Integer, Field> hashFields = DirectoryUtils.getMapFieldsOfListEntry(listEntryResultSearch, getPlugin());

    StringBuffer strBufferListRecordXml = null;

    java.io.File tmpFile = null;
    BufferedWriter bufferedWriter = null;
    OutputStreamWriter outputStreamWriter = null;

    File fileTemplate = null;
    String strFileOutPut = DirectoryUtils.EMPTY_STRING;

    if (directoryXsl.getFile() != null) {
        fileTemplate = FileHome.findByPrimaryKey(directoryXsl.getFile().getIdFile(), getPlugin());
    }

    XmlTransformerService xmlTransformerService = null;
    PhysicalFile physicalFile = null;
    String strXslId = null;

    if ((fileTemplate != null) && (fileTemplate.getPhysicalFile() != null)) {
        fileTemplate.setPhysicalFile(PhysicalFileHome
                .findByPrimaryKey(fileTemplate.getPhysicalFile().getIdPhysicalFile(), getPlugin()));

        xmlTransformerService = new XmlTransformerService();
        physicalFile = fileTemplate.getPhysicalFile();
        strXslId = XSL_UNIQUE_PREFIX_ID + physicalFile.getIdPhysicalFile();
    }

    int nSize = listResultRecordId.size();
    boolean bIsBigExport = (nSize > EXPORT_RECORD_STEP);

    // Encoding export
    String strEncoding = StringUtils.EMPTY;

    if (bIsCsvExport) {
        strEncoding = DirectoryParameterService.getService().getExportCSVEncoding();
    } else {
        strEncoding = DirectoryParameterService.getService().getExportXMLEncoding();
    }

    if (bIsBigExport) {
        try {
            String strPath = AppPathService.getWebAppPath()
                    + AppPropertiesService.getProperty(PROPERTY_PATH_TMP);
            java.io.File tmpDir = new java.io.File(strPath);
            tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX, tmpDir);
        } catch (IOException e) {
            AppLogService.error("Unable to create temp file in webapp tmp dir");

            try {
                tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX);
            } catch (IOException e1) {
                AppLogService.error(e1);
            }
        }

        try {
            tmpFile.deleteOnExit();
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), strEncoding);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
        } catch (IOException e) {
            AppLogService.error(e);
        }
    }

    Plugin plugin = this.getPlugin();
    Locale locale = request.getLocale();

    // ---------------------------------------------------------------------
    StringBuffer strBufferListEntryXml = new StringBuffer();

    if (bDisplayDateCreation && bIsCsvExport) {
        Map<String, String> model = new HashMap<String, String>();
        model.put(Entry.ATTRIBUTE_ENTRY_ID, "0");
        XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model);

        String strDateCreation = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_CREATION_TITLE,
                locale);
        XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateCreation);
        XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY);
    }

    if (bDisplayDateModification && bIsCsvExport) {
        Map<String, String> model = new HashMap<String, String>();
        model.put(Entry.ATTRIBUTE_ENTRY_ID, "0");
        XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model);

        String strDateModification = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_MODIFICATION_TITLE,
                locale);
        XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateModification);
        XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY);
    }

    for (IEntry entry : listEntryResultSearch) {
        entry.getXml(plugin, locale, strBufferListEntryXml);
    }

    Map<String, String> model = new HashMap<String, String>();

    if ((directory.getIdWorkflow() != DirectoryUtils.CONSTANT_ID_NULL) && bWorkflowServiceEnable) {
        model.put(TAG_DISPLAY, TAG_YES);
    } else {
        model.put(TAG_DISPLAY, TAG_NO);
    }

    XmlUtil.addEmptyElement(strBufferListEntryXml, TAG_STATUS, model);

    StringBuilder strBufferDirectoryXml = new StringBuilder();
    strBufferDirectoryXml.append(XmlUtil.getXmlHeader());

    if (bIsBigExport) {
        strBufferDirectoryXml
                .append(directory.getXml(plugin, locale, new StringBuffer(), strBufferListEntryXml));

        strBufferListRecordXml = new StringBuffer(EXPORT_STRINGBUFFER_INITIAL_SIZE);

        strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferDirectoryXml.toString(),
                physicalFile.getValue(), strXslId, null, null);

        String strFinalOutPut = null;

        if (!bIsCsvExport) {
            int pos = strFileOutPut.indexOf(EXPORT_XSL_EMPTY_LIST_RECORD);
            strFinalOutPut = strFileOutPut.substring(0, pos) + EXPORT_XSL_BEGIN_LIST_RECORD;
        } else {
            strFinalOutPut = strFileOutPut;
        }

        try {
            bufferedWriter.write(strFinalOutPut);
        } catch (IOException e) {
            AppLogService.error(e);
        }
    } else {
        strBufferListRecordXml = new StringBuffer();
    }

    // -----------------------------------------------------------------------
    List<Integer> nTmpListId = new ArrayList<Integer>();
    int idWorflow = directory.getIdWorkflow();
    IRecordService recordService = SpringContextService.getBean(RecordService.BEAN_SERVICE);

    if (bIsBigExport) {
        int nXmlHeaderLength = XmlUtil.getXmlHeader().length() - 1;
        int max = nSize / EXPORT_RECORD_STEP;
        int max1 = nSize - EXPORT_RECORD_STEP;

        for (int i = 0; i < max1; i += EXPORT_RECORD_STEP) {
            AppLogService.debug("Directory export progress : " + (((float) i / nSize) * 100) + "%");

            nTmpListId = new ArrayList<Integer>();

            int k = i + EXPORT_RECORD_STEP;

            for (int j = i; j < k; j++) {
                nTmpListId.add(listResultRecordId.get(j));
            }

            List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin);

            for (Record record : nTmpListRecords) {
                State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                        idWorflow, Integer.valueOf(directory.getIdDirectory()));

                if (bIsCsvExport) {
                    strBufferListRecordXml.append(record.getXmlForCsvExport(plugin, locale, false, state,
                            listEntryResultSearch, false, false, true, bDisplayDateCreation,
                            bDisplayDateModification, hashFields));
                } else {
                    strBufferListRecordXml
                            .append(record.getXml(plugin, locale, false, state, listEntryResultSearch, false,
                                    false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
                }
            }

            strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter,
                    physicalFile, bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService);
        }

        // -----------------------------------------------------------------------
        int max2 = EXPORT_RECORD_STEP * max;
        nTmpListId = new ArrayList<Integer>();

        for (int i = max2; i < nSize; i++) {
            nTmpListId.add(listResultRecordId.get((i)));
        }

        List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin);

        for (Record record : nTmpListRecords) {
            State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                    idWorflow, Integer.valueOf(directory.getIdDirectory()));

            if (bIsCsvExport) {
                strBufferListRecordXml.append(
                        record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false,
                                false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            } else {
                strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch,
                        false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            }
        }

        strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter, physicalFile,
                bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService);

        strBufferListRecordXml.insert(0, EXPORT_XSL_BEGIN_PARTIAL_EXPORT);
        strBufferListRecordXml.insert(0, XmlUtil.getXmlHeader());
        strBufferListRecordXml.append(EXPORT_XSL_END_PARTIAL_EXPORT);
        strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferListRecordXml.toString(),
                physicalFile.getValue(), strXslId, null, null);

        try {
            if (bIsCsvExport) {
                bufferedWriter.write(strFileOutPut);
            } else {
                bufferedWriter.write(strFileOutPut.substring(nXmlHeaderLength));
                bufferedWriter
                        .write(EXPORT_XSL_END_LIST_RECORD + EXPORT_XSL_NEW_LINE + EXPORT_XSL_END_DIRECTORY);
            }
        } catch (IOException e) {
            AppLogService.error(e);
        } finally {
            IOUtils.closeQuietly(bufferedWriter);
            IOUtils.closeQuietly(outputStreamWriter);
        }
    } else {
        List<Record> nTmpListRecords = recordService.loadListByListId(listResultRecordId, plugin);

        for (Record record : nTmpListRecords) {
            State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                    idWorflow, Integer.valueOf(directory.getIdDirectory()));

            if (bIsCsvExport) {
                strBufferListRecordXml.append(
                        record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false,
                                false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            } else {
                strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch,
                        false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            }
        }

        strBufferDirectoryXml
                .append(directory.getXml(plugin, locale, strBufferListRecordXml, strBufferListEntryXml));
        strShotExportFinalOutPut = xmlTransformerService.transformBySourceWithXslCache(
                strBufferDirectoryXml.toString(), physicalFile.getValue(), strXslId, null, null);
    }

    // ----------------------------------------------------------------------- 
    DirectoryUtils.addHeaderResponse(request, response, strFileName);
    response.setCharacterEncoding(strEncoding);

    if (bIsCsvExport) {
        response.setContentType(CONSTANT_MIME_TYPE_CSV);
    } else {
        String strMimeType = FileSystemUtil.getMIMEType(strFileName);

        if (strMimeType != null) {
            response.setContentType(strMimeType);
        } else {
            response.setContentType(CONSTANT_MIME_TYPE_OCTETSTREAM);
        }
    }

    if (bIsBigExport) {
        FileChannel in = null;
        WritableByteChannel writeChannelOut = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(tmpFile).getChannel();
            out = response.getOutputStream();
            writeChannelOut = Channels.newChannel(out);
            response.setContentLength(Long.valueOf(in.size()).intValue());
            in.transferTo(0, in.size(), writeChannelOut);
            response.getOutputStream().close();
        } catch (IOException e) {
            AppLogService.error(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    AppLogService.error(e.getMessage(), e);
                }
            }

            IOUtils.closeQuietly(out);

            tmpFile.delete();
        }
    } else {
        PrintWriter out = null;

        try {
            out = response.getWriter();
            out.print(strShotExportFinalOutPut);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    result.setNoop(true);

    return result;
}

From source file:com.facebook.infrastructure.net.TcpConnection.java

public void stream(File file, long startPosition, long endPosition) throws IOException {
    if (!bStream_)
        throw new IllegalStateException("Cannot stream since we are not set up to stream data.");

    lock_.lock();/*  ww w .  j  a v a2  s . com*/
    try {
        /* transfer 64MB in each attempt */
        int limit = 64 * 1024 * 1024;
        long total = endPosition - startPosition;
        /* keeps track of total number of bytes transferred */
        long bytesWritten = 0L;
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel fc = raf.getChannel();

        /* 
         * If the connection is not yet established then wait for
         * the timeout period of 2 seconds. Attempt to reconnect 3 times and then 
         * bail with an IOException.
        */
        long waitTime = 2;
        int retry = 0;
        while (!connected_.get()) {
            if (retry == 3)
                throw new IOException("Unable to connect to " + remoteEp_ + " after " + retry + " attempts.");
            waitToContinueStreaming(waitTime, TimeUnit.SECONDS);
            ++retry;
        }

        while (bytesWritten < total) {
            if (startPosition == 0) {
                ByteBuffer buffer = MessagingService.constructStreamHeader(false, true);
                socketChannel_.write(buffer);
                handleIncompleteWrite(buffer);
            }

            /* returns the number of bytes transferred from file to the socket */
            long bytesTransferred = fc.transferTo(startPosition, limit, socketChannel_);
            logger_.trace("Bytes transferred " + bytesTransferred);
            bytesWritten += bytesTransferred;
            startPosition += bytesTransferred;
            /*
             * If the number of bytes transferred is less than intended 
             * then we need to wait till socket becomes writeable again. 
            */
            if (bytesTransferred < limit && bytesWritten != total) {
                if ((key_.interestOps() & SelectionKey.OP_WRITE) == 0) {
                    SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
                }
                waitToContinueStreaming();
            }
        }
    } finally {
        lock_.unlock();
    }
}