Example usage for java.nio.channels FileChannel close

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

Introduction

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

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

private void closeChannel(int logNumber) throws NeedleManagerException {
    FileChannel fc = channelMap.get(logNumber);
    if (fc == null)
        return;//w  ww . j a va  2  s  . co m
    try {
        fc.close();
    } catch (IOException ie) {
        logger.error("Error closing log channel " + Integer.toHexString(logNumber));
        throw new NeedleManagerException("Error closing log channel " + Integer.toHexString(logNumber), ie);
    }
    channelMap.remove(new Integer(logNumber));
}

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

/**
 * use for copy images given in an array in a folder given in parameters
 * @param images//from ww w  . j  a  v a2s  .co m
 * @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:org.rhq.plugins.jslee.JainSleeServerComponent.java

private void copyFile(File sourceFile, File destFile) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath()
                + "]");
    }//from   w w w. j  ava 2 s  .c o  m

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:org.alfresco.repo.content.AbstractContentWriter.java

/**
 * {@inheritDoc}/*from   www . ja  v  a 2  s.  co  m*/
 */
public FileChannel getFileChannel(boolean truncate) throws ContentIOException {
    /*
     * By calling this method, clients indicate that they wish to make random
     * changes to the file.  It is possible that the client might only want
     * to update a tiny proportion of the file (truncate == false) or
     * start afresh (truncate == true).
     * 
     * Where the underlying support is not present for this method, a temporary
     * file will be used as a substitute.  When the write is complete, the
     * results are copied directly to the underlying channel.
     */

    // get the underlying implementation's best writable channel
    channel = getWritableChannel();
    // now use this channel if it can provide the random access, otherwise spoof it
    FileChannel clientFileChannel = null;
    if (channel instanceof FileChannel) {
        // all the support is provided by the underlying implementation
        clientFileChannel = (FileChannel) channel;
        // copy over the existing content, if required
        if (!truncate && existingContentReader != null) {
            ReadableByteChannel existingContentChannel = existingContentReader.getReadableChannel();
            long existingContentLength = existingContentReader.getSize();
            // copy the existing content
            try {
                clientFileChannel.transferFrom(existingContentChannel, 0, existingContentLength);
                // copy complete
                if (logger.isDebugEnabled()) {
                    logger.debug("Copied content for random access: \n" + "   writer: " + this + "\n"
                            + "   existing: " + existingContentReader);
                }
            } catch (IOException e) {
                throw new ContentIOException("Failed to copy from existing content to enable random access: \n"
                        + "   writer: " + this + "\n" + "   existing: " + existingContentReader, e);
            } finally {
                try {
                    existingContentChannel.close();
                } catch (IOException e) {
                }
            }
        }
        // debug
        if (logger.isDebugEnabled()) {
            logger.debug("Content writer provided direct support for FileChannel: \n" + "   writer: " + this);
        }
    } else {
        // No random access support is provided by the implementation.
        // Spoof it by providing a 2-stage write via a temp file
        File tempFile = TempFileProvider.createTempFile("random_write_spoof_", ".bin");
        final FileContentWriter spoofWriter = new FileContentWriter(tempFile, // the file to write to
                getExistingContentReader()); // this ensures that the existing content is pulled in
        // Attach a listener
        // - to ensure that the content gets loaded from the temp file once writing has finished
        // - to ensure that the close call gets passed on to the underlying channel
        ContentStreamListener spoofListener = new ContentStreamListener() {
            public void contentStreamClosed() throws ContentIOException {
                // the spoofed temp channel has been closed, so get a new reader for it
                ContentReader spoofReader = spoofWriter.getReader();
                FileChannel spoofChannel = spoofReader.getFileChannel();
                // upload all the temp content to the real underlying channel
                try {
                    long spoofFileSize = spoofChannel.size();
                    spoofChannel.transferTo(0, spoofFileSize, channel);
                } catch (IOException e) {
                    throw new ContentIOException(
                            "Failed to copy from spoofed temporary channel to permanent channel: \n"
                                    + "   writer: " + this + "\n" + "   temp: " + spoofReader,
                            e);
                } finally {
                    try {
                        spoofChannel.close();
                    } catch (Throwable e) {
                    }
                    try {
                        channel.close();
                    } catch (IOException e) {
                        throw new ContentIOException("Failed to close underlying channel", e);
                    }
                }
            }
        };
        spoofWriter.addListener(spoofListener);
        // we now have the spoofed up channel that the client can work with
        clientFileChannel = spoofWriter.getFileChannel(truncate);
        // debug
        if (logger.isDebugEnabled()) {
            logger.debug("Content writer provided indirect support for FileChannel: \n" + "   writer: " + this
                    + "\n" + "   temp writer: " + spoofWriter);
        }
    }
    // the file is now available for random access
    return clientFileChannel;
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Copy file from one location to another. Will silently overwrite an
 * already existing file./*w ww.j a va  2 s . c  om*/
 *
 * @param from
 *            original to copy
 * @param to
 *            destination of copy
 * @throws IOFailure if an io error occurs while copying file,
 * or the original file does not exist.
 */
public static void copyFile(File from, File to) {
    ArgumentNotValid.checkNotNull(from, "File from");
    ArgumentNotValid.checkNotNull(to, "File to");
    if (!from.exists()) {
        String errMsg = "Original file '" + from.getAbsolutePath() + "' does not exist";
        log.warn(errMsg);
        throw new IOFailure(errMsg);
    }
    try {
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            inStream = new FileInputStream(from);
            outStream = new FileOutputStream(to);
            in = inStream.getChannel();
            out = outStream.getChannel();
            long bytesTransferred = 0;
            do {
                //Note: in.size() is called every loop, because if it should
                //change size, we might end up in an infinite loop trying to
                //copy more bytes than are actually available.
                bytesTransferred += in.transferTo(bytesTransferred,
                        Math.min(Constants.IO_CHUNK_SIZE, in.size() - bytesTransferred), out);
            } while (bytesTransferred < in.size());
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    } catch (IOException e) {
        final String errMsg = "Error copying file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath()
                + "'";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    }
}

From source file:org.ops4j.pax.runner.platform.internal.PlatformImpl.java

/**
 * Downloads files from urls./*from   w  w  w.  j a v  a  2  s.  c  o m*/
 *
 * @param workDir          the directory where to download bundles
 * @param url              of the file to be downloaded
 * @param displayName      to be shown during download
 * @param overwrite        if the bundles should be overwritten
 * @param checkAttributes  whether or not to check attributes in the manifest
 * @param failOnValidation if validation fails should or not fail with an exception (or just return null)
 * @param downloadFeeback  whether or not downloading process should display fine grained progres info
 *
 * @return the File corresponding to the downloaded file, or null if the bundle is invalid (not an osgi bundle)
 *
 * @throws PlatformException if the url could not be downloaded
 */
private File download(final File workDir, final URL url, final String displayName, final Boolean overwrite,
        final boolean checkAttributes, final boolean failOnValidation, final boolean downloadFeeback)
        throws PlatformException {
    LOGGER.debug("Downloading [" + url + "]");
    File downloadedBundlesFile = new File(workDir, "bundles/downloaded_bundles.properties");
    Properties fileNamesForUrls = loadProperties(downloadedBundlesFile);

    String downloadedFileName = fileNamesForUrls.getProperty(url.toExternalForm());
    String hashFileName = "" + url.toExternalForm().hashCode();
    if (downloadedFileName == null) {
        // destination will be made based on the hashcode of the url to be downloaded
        downloadedFileName = hashFileName + ".jar";

    }
    File destination = new File(workDir, "bundles/" + downloadedFileName);

    // download the bundle only if is a forced overwrite or the file does not exist or the file is there but is
    // invalid
    boolean forceOverwrite = overwrite || !destination.exists();
    if (!forceOverwrite) {
        try {
            String cachingName = determineCachingName(destination, hashFileName);
            if (!destination.getName().equals(cachingName)) {
                throw new PlatformException("File " + destination + " should have name " + cachingName);
            }
        } catch (PlatformException ignore) {
            forceOverwrite = true;
        }
    }
    if (forceOverwrite) {
        try {
            LOGGER.debug("Creating new file at destination: " + destination.getAbsolutePath());
            destination.getParentFile().mkdirs();
            destination.createNewFile();
            FileOutputStream os = null;
            try {
                os = new FileOutputStream(destination);
                FileChannel fileChannel = os.getChannel();
                StreamUtils.ProgressBar progressBar = null;
                if (LOGGER.isInfoEnabled()) {
                    if (downloadFeeback) {
                        progressBar = new StreamUtils.FineGrainedProgressBar(displayName);
                    } else {
                        progressBar = new StreamUtils.CoarseGrainedProgressBar(displayName);
                    }
                }
                StreamUtils.streamCopy(url, fileChannel, progressBar);
                fileChannel.close();
                LOGGER.debug("Succesfully downloaded to [" + destination + "]");
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        } catch (IOException e) {
            throw new PlatformException("[" + url + "] could not be downloaded", e);
        }
    }
    if (checkAttributes) {
        try {
            validateBundle(url, destination);
        } catch (PlatformException e) {
            if (failOnValidation) {
                throw e;
            }
            return null;
        }
    }
    String cachingName = determineCachingName(destination, hashFileName);
    File newDestination = new File(destination.getParentFile(), cachingName);
    if (!cachingName.equals(destination.getName())) {
        if (newDestination.exists()) {
            if (!newDestination.delete()) {
                throw new PlatformException("Cannot delete " + newDestination);
            }
        }
        if (!destination.renameTo(newDestination)) {
            throw new PlatformException("Cannot rename " + destination + " to " + newDestination);
        }
        fileNamesForUrls.setProperty(url.toExternalForm(), cachingName);
        saveProperties(fileNamesForUrls, downloadedBundlesFile);
    }

    return newDestination;
}

From source file:de.baumann.quitsmoking.fragments.FragmentNotes.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_backup) {

        final CharSequence[] options = { getString(R.string.action_backup), getString(R.string.action_restore),
                getString(R.string.action_delete) };

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override/*  w  w w . ja  v  a 2s. c o m*/
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals(getString(R.string.action_backup))) {

                    sharedPref.edit().putString("sortDB", "title").apply();
                    setNotesList();

                    File directory = new File(
                            Environment.getExternalStorageDirectory() + "/QuitSmoking/backup/");
                    if (!directory.exists()) {
                        //noinspection ResultOfMethodCallIgnored
                        directory.mkdirs();
                    }

                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        File data = Environment.getDataDirectory();

                        if (sd.canWrite()) {

                            String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//"
                                    + "notes.db";
                            String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db";
                            File currentDB2 = new File(data, currentDBPath2);
                            File backupDB2 = new File(sd, backupDBPath2);

                            FileChannel src2 = new FileInputStream(currentDB2).getChannel();
                            FileChannel dst2 = new FileOutputStream(backupDB2).getChannel();
                            dst2.transferFrom(src2, 0, src2.size());
                            src2.close();
                            dst2.close();

                            Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup,
                                    Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }
                    } catch (Exception e) {
                        Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup_not,
                                Snackbar.LENGTH_LONG);
                        snackbar.show();
                    }
                }

                if (options[item].equals(getString(R.string.action_restore))) {

                    sharedPref.edit().putString("sortDB", "seqno").apply();
                    setNotesList();

                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        File data = Environment.getDataDirectory();

                        if (sd.canWrite()) {

                            String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//"
                                    + "notes.db";
                            String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db";
                            File currentDB2 = new File(data, currentDBPath2);
                            File backupDB2 = new File(sd, backupDBPath2);

                            FileChannel src2 = new FileInputStream(backupDB2).getChannel();
                            FileChannel dst2 = new FileOutputStream(currentDB2).getChannel();
                            dst2.transferFrom(src2, 0, src2.size());
                            src2.close();
                            dst2.close();
                            Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore,
                                    Snackbar.LENGTH_LONG);
                            snackbar.show();
                            setNotesList();
                        }
                    } catch (Exception e) {
                        Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore_not,
                                Snackbar.LENGTH_LONG);
                        snackbar.show();
                    }
                }

                if (options[item].equals(getString(R.string.action_delete))) {

                    sharedPref.edit().putString("sortDB", "icon").apply();
                    setNotesList();

                    Snackbar snackbar = Snackbar
                            .make(listView, R.string.note_delete_confirmation, Snackbar.LENGTH_LONG)
                            .setAction(R.string.yes, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    getActivity().deleteDatabase("notes.db");
                                    setNotesList();
                                }
                            });
                    snackbar.show();
                }
            }
        });
        builder.setPositiveButton(R.string.goal_cancel, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    if (id == R.id.action_sort) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View dialogView = View.inflate(getActivity(), R.layout.dialog_sort, null);

        final CheckBox ch_title = (CheckBox) dialogView.findViewById(R.id.checkBoxTitle);
        final CheckBox ch_create = (CheckBox) dialogView.findViewById(R.id.checkBoxCreate);
        final CheckBox ch_edit = (CheckBox) dialogView.findViewById(R.id.checkBoxEdit);
        final CheckBox ch_icon = (CheckBox) dialogView.findViewById(R.id.checkBoxIcon);
        final CheckBox ch_att = (CheckBox) dialogView.findViewById(R.id.checkBoxAtt);

        if (sharedPref.getString("sortDB", "title").equals("title")) {
            ch_title.setChecked(true);
        } else {
            ch_title.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("create")) {
            ch_create.setChecked(true);
        } else {
            ch_create.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("seqno")) {
            ch_edit.setChecked(true);
        } else {
            ch_edit.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("icon")) {
            ch_icon.setChecked(true);
        } else {
            ch_icon.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("attachment")) {
            ch_att.setChecked(true);
        } else {
            ch_att.setChecked(false);
        }

        ch_title.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "title").apply();
                    setNotesList();
                }
            }
        });
        ch_create.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_edit.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "create").apply();
                    setNotesList();
                }
            }
        });
        ch_edit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "seqno").apply();
                    setNotesList();
                }
            }
        });
        ch_icon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "icon").apply();
                    setNotesList();
                }
            }
        });
        ch_att.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_title.setChecked(false);
                    ch_icon.setChecked(false);
                    sharedPref.edit().putString("sortDB", "attachment").apply();
                    setNotesList();
                }
            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.action_sort);
        builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });

        final AlertDialog dialog2 = builder.create();
        // Display the custom alert dialog on interface
        dialog2.show();
        return true;
    }

    if (id == R.id.action_note) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        String dateCreate = format.format(date);
        sharedPref.edit().putString("handleTextCreate", dateCreate).apply();

        helper_notes.editNote(getActivity());

    }

    return super.onOptionsItemSelected(item);
}

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 {//www. j  ava2s  . co m

        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.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testFileTruncatedBetweenRuns() throws Exception {
    File testDataDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir.mkdirs());
    File file = new File(testDataDir, "file.txt-1");
    Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8);

    FileInfo fileInfo = new FileInfo();
    fileInfo.fileFullPath = testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}";
    fileInfo.fileRollMode = FileRollMode.PATTERN;
    fileInfo.firstFile = "";
    fileInfo.patternForToken = "[0-9]";
    Source source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}",
            "[0-9]");
    SourceRunner runner = createRunner(source);
    try {//  w  w w.j  a  va2 s .c o m
        // run till current end and stop pipeline
        runner.runInit();
        StageRunner.Output output = runner.runProduce(null, 10);
        Assert.assertEquals(3, output.getRecords().get("lane").size());
        runner.runDestroy();

        // truncate file
        FileChannel channel = new FileOutputStream(file, true).getChannel();
        channel.truncate(2);
        channel.close();

        // run again, no new data, no error
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(0, output.getRecords().get("lane").size());
        runner.runDestroy();

        file = new File(testDataDir, "file.txt-2");
        Files.write(file.toPath(), Arrays.asList("A", "B"), StandardCharsets.UTF_8);

        // run again, new file
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(2, output.getRecords().get("lane").size());

    } finally {
        runner.runDestroy();
    }
}

From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java

private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException {

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from   ww w.j  a v a  2s  .co  m*/

    byte[] golden = new byte[0];

    // search skins for the jsp and write it out to "golden"
    for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) {

        if (null == site) {
            if (null == config.getServletContext().getResource(jsp)) {
                throw new ResourceLoadException("Unable to find " + jsp + " in any skin");
            }
            break;
        }

        final Site finalSite = site;
        final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp,
                null);
        bcLoader.abut();
        golden = bcLoader.getBytecode();
    }

    // if golden now contains data save it to a local (ie local web application) file
    if (0 < golden.length) {
        try {
            final File file = new File(root + jsp);

            // create the directory structure
            file.getParentFile().mkdirs();

            // check existing file
            boolean needsUpdating = true;
            final boolean fileExisted = file.exists();
            if (!fileExisted) {
                file.createNewFile();
            }

            // channel.lock() only synchronises file access between programs, but not between threads inside
            //  the current JVM. The latter results in the OverlappingFileLockException.
            //  At least this is my current understanding of java.nio.channels
            //   It may be that no synchronisation or locking is required at all. A beer to whom answers :-)
            // So we must provide synchronisation between our own threads,
            //  synchronisation against the file's path (using the JVM's String.intern() functionality)
            //  should work. (I can't imagine this string be used for any other synchronisation purposes).
            synchronized (file.toString().intern()) {

                RandomAccessFile fileAccess = null;
                FileChannel channel = null;

                try {

                    fileAccess = new RandomAccessFile(file, "rws");
                    channel = fileAccess.getChannel();

                    channel.lock();

                    if (fileExisted) {

                        final byte[] bytes = new byte[(int) channel.size()];
                        final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
                        int reads;
                        do {
                            reads = channel.read(byteBuffer);
                        } while (0 < reads);

                        needsUpdating = !Arrays.equals(golden, bytes);
                    }

                    if (needsUpdating) {
                        // download file from skin
                        channel.write(ByteBuffer.wrap(golden), 0);
                        file.deleteOnExit();
                    }
                } finally {
                    if (null != channel) {
                        channel.close();
                    }
                    if (null != fileAccess) {
                        fileAccess.close();
                    }

                    LOG.debug("resource created as " + config.getServletContext().getResource(jsp));
                }
            }

        } catch (IOException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }

    stopWatch.stop();
    LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch);
}