Search in sources :

Example 16 with PosixFileAttributes

use of java.nio.file.attribute.PosixFileAttributes in project ignite by apache.

the class IgfsLocalSecondaryFileSystemTestAdapter method properties.

/**
 * {@inheritDoc}
 */
@Override
public Map<String, String> properties(final String path) throws IOException {
    Path p = path(path);
    PosixFileAttributes attrs = Files.getFileAttributeView(p, PosixFileAttributeView.class).readAttributes();
    Map<String, String> props = new HashMap<>();
    props.put(IgfsUtils.PROP_USER_NAME, attrs.owner().getName());
    props.put(IgfsUtils.PROP_GROUP_NAME, attrs.group().getName());
    props.put(IgfsUtils.PROP_PERMISSION, permissions(path));
    return props;
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Example 17 with PosixFileAttributes

use of java.nio.file.attribute.PosixFileAttributes in project pravega by pravega.

the class FileSystemStorage method doGetStreamSegmentInfo.

private SegmentProperties doGetStreamSegmentInfo(String streamSegmentName) throws IOException {
    long traceId = LoggerHelpers.traceEnter(log, "getStreamSegmentInfo", streamSegmentName);
    PosixFileAttributes attrs = Files.readAttributes(Paths.get(config.getRoot(), streamSegmentName), PosixFileAttributes.class);
    StreamSegmentInformation information = StreamSegmentInformation.builder().name(streamSegmentName).length(attrs.size()).sealed(!(attrs.permissions().contains(OWNER_WRITE))).lastModified(new ImmutableDate(attrs.creationTime().toMillis())).build();
    LoggerHelpers.traceLeave(log, "getStreamSegmentInfo", traceId, streamSegmentName);
    return information;
}
Also used : StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) ImmutableDate(io.pravega.common.util.ImmutableDate) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes)

Example 18 with PosixFileAttributes

use of java.nio.file.attribute.PosixFileAttributes in project FinalCrypt by ron-from-nl.

the class FinalCrypt method encryptSelection.

public void encryptSelection(FCPathList targetSourcePathList, FCPathList filteredTargetSourcePathList, FCPath cipherSourceFCPath, boolean encryptmode) {
    startCalendar = Calendar.getInstance(Locale.ROOT);
    if (cipherSourceFCPath.size < bufferSize) {
        setBufferSize((int) cipherSourceFCPath.size);
    }
    Stats allDataStats = new Stats();
    allDataStats.reset();
    Stat readTargetSourceStat = new Stat();
    readTargetSourceStat.reset();
    // Stat readCipherSourceStat = new Stat(); readCipherSourceStat.reset();
    // Stat wrteTargetDestinStat = new Stat(); wrteTargetDestinStat.reset();
    // Stat readTargetDestinStat = new Stat(); readTargetDestinStat.reset();
    Stat wrteTargetSourceStat = new Stat();
    wrteTargetSourceStat.reset();
    stopPending = false;
    pausing = false;
    // Get TOTALS
    allDataStats.setFilesTotal(filteredTargetSourcePathList.encryptableFiles + filteredTargetSourcePathList.decryptableFiles);
    allDataStats.setAllDataBytesTotal(filteredTargetSourcePathList.encryptableFilesSize + filteredTargetSourcePathList.decryptableFilesSize);
    ui.status(allDataStats.getStartSummary("En/Decrypting"), true);
    try {
        Thread.sleep(100);
    } catch (InterruptedException ex) {
    }
    // Setup the Progress TIMER & TASK
    updateProgressTask = new TimerTask() {

        private long bytesTotal;

        private long bytesProcessed;

        @Override
        public void run() {
            long fileBytesProcessed = (readTargetSourceStat.getFileBytesProcessed() + wrteTargetSourceStat.getFileBytesProcessed());
            // 1000 / 100 = (long)10     10 > 0.1 (10*0.01)
            double fileBytesPercent = ((readTargetSourceStat.getFileBytesTotal()) / 100.0);
            // 600 / 10 = 60 - 600 * (10*0.01)
            int fileBytesPercentage = (int) (fileBytesProcessed / fileBytesPercent);
            long filesBytesProcessed = (allDataStats.getFilesBytesProcessed());
            double filesBytesPercent = ((allDataStats.getFilesBytesTotal()) / 100.0);
            int filesBytesPercentage = (int) (filesBytesProcessed / filesBytesPercent);
            processProgressCalendar = Calendar.getInstance(Locale.ROOT);
            bytesTotal = allDataStats.getFilesBytesTotal();
            bytesProcessed = allDataStats.getFileBytesProcessed();
            bytesPerMilliSecond = filesBytesProcessed / (processProgressCalendar.getTimeInMillis() - startCalendar.getTimeInMillis());
            ui.processProgress(fileBytesPercentage, filesBytesPercentage, bytesTotal, bytesProcessed, bytesPerMilliSecond);
        }
    };
    updateProgressTaskTimer = new java.util.Timer();
    updateProgressTaskTimer.schedule(updateProgressTask, 100L, 100L);
    // Start Files Encryption Clock
    allDataStats.setAllDataStartNanoTime();
    encryptTargetloop: for (Iterator it = filteredTargetSourcePathList.iterator(); it.hasNext(); ) {
        FCPath newTargetSourceFCPath = (FCPath) it.next();
        FCPath oldTargetSourceFCPath = newTargetSourceFCPath.clone(newTargetSourceFCPath);
        Path targetDestinPath = null;
        String fileStatusLine = "";
        // long targetSourceSize = 0; try { targetSourceSize = Files.size(targetSourcePath); } catch (IOException ex) { ui.error("Error: Files.size(targetSourcePath); " + ex.getMessage() + "\r\n"); continue encryptTargetloop; }
        if (stopPending) {
            targetSourceEnded = true;
            break encryptTargetloop;
        }
        // isValidFile(UI ui, String caller, Path targetSourcePath, boolean device, long minSize, boolean symlink, boolean writable, boolean report)
        if ((newTargetSourceFCPath.path.compareTo(cipherSourceFCPath.path) != 0)) {
            String bit_extension = ".bit";
            // -1 no extension
            int lastDotPos = newTargetSourceFCPath.path.getFileName().toString().lastIndexOf('.');
            int lastPos = newTargetSourceFCPath.path.getFileName().toString().length();
            String extension = "";
            if (lastDotPos != -1) {
                extension = newTargetSourceFCPath.path.getFileName().toString().substring(lastDotPos, lastPos);
            } else {
                extension = "";
            }
            if (encryptmode) {
                targetDestinPath = newTargetSourceFCPath.path.resolveSibling(newTargetSourceFCPath.path.getFileName().toString() + bit_extension);
            } else // (decryptmode)
            {
                // if (extension.equals(bit_extension))    { targetDestinPath = newTargetSourceFCPath.path.resolveSibling(newTargetSourceFCPath.path.getFileName().toString().replace(bit_extension, "")); }
                if (extension.equals(bit_extension)) {
                    targetDestinPath = Paths.get(newTargetSourceFCPath.path.toString().substring(0, newTargetSourceFCPath.path.toString().lastIndexOf('.')));
                } else {
                    targetDestinPath = newTargetSourceFCPath.path.resolveSibling(newTargetSourceFCPath.path.getFileName().toString() + bit_extension);
                }
            }
            try {
                Files.deleteIfExists(targetDestinPath);
            } catch (IOException ex) {
                ui.error("Error: Files.deleteIfExists(targetDestinPath): " + ex.getMessage() + "\r\n");
            }
            // Prints printByte Header ones
            if (print) {
                ui.log("\r\n");
                ui.log(" ----------------------------------------------------------------------\r\n");
                ui.log("|          |       Input       |      Cipher       |      Output       |\r\n");
                ui.log("| ---------|-------------------|-------------------|-------------------|\r\n");
                ui.log("| adr      | bin      hx dec c | bin      hx dec c | bin      hx dec c |\r\n");
                ui.log("|----------|-------------------|-------------------|-------------------|\r\n");
            }
            // ___________________________________________________________________________________________________________________________________________________________
            // 
            // Testing FinalCrypt Token
            // 🔒   Encrypt
            // 🔓   Decrypt	    (Cipher Authenticated)
            // 🔓!  Decrypt Legacy  (Cipher can't be checked! No Token present in old format)
            // â›”   Decrypt Abort   (Cipher Failed)
            long readTargetSourceChannelPosition = 0;
            long writeTargetDestChannelTransfered = 0;
            if (encryptmode) {
                if (// Target has NO Token, Decrypted
                newTargetSourceFCPath.isDecrypted) {
                    if (// TargetSource is (Encryptable)
                    newTargetSourceFCPath.isEncryptable) {
                        ui.status("🔒 \"" + targetDestinPath.toString() + "\" ", false);
                        fileStatusLine = "🔒 \"" + targetDestinPath.toString() + "\" ";
                        if (!dry) {
                            // Add Token to targetDestinPath
                            ByteBuffer targetDestinTokenBuffer = ByteBuffer.allocate((FINALCRYPT_PLAIN_IEXT_AUTHENTICATION_TOKEN.length() * 2));
                            targetDestinTokenBuffer.clear();
                            try (final SeekableByteChannel writeTargetDestinChannel = Files.newByteChannel(targetDestinPath, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC))) {
                                targetDestinTokenBuffer = createTargetDestinToken(cipherSourceFCPath.path);
                                writeTargetDestChannelTransfered = writeTargetDestinChannel.write(targetDestinTokenBuffer);
                                targetDestinTokenBuffer.flip();
                                writeTargetDestinChannel.close();
                            // wrteTargetDestinStat.addFileBytesProcessed(writeTargetDestChannelTransfered);
                            } catch (IOException ex) {
                                ui.error("Error: Add Token writeTargetDestinChannel Abort Encrypting: " + targetDestinPath.toString() + " " + ex.getMessage() + "\r\n");
                                continue encryptTargetloop;
                            }
                        }
                    } else {
                        ui.status("âš  \"" + newTargetSourceFCPath.toString() + "\" - Not Encryptable!\r\n", true);
                        continue encryptTargetloop;
                    }
                }
            } else {
                if (// Target has Token, Decrypt New Format
                newTargetSourceFCPath.isEncrypted) {
                    if (// TargetSource Has Authenticated Token (Decryptable)
                    newTargetSourceFCPath.isDecryptable) {
                        fileStatusLine = "🔓 \"" + targetDestinPath.toString() + "\" ";
                        ui.status("🔓 \"" + targetDestinPath.toString() + "\" ", false);
                        // Decrypt skipping Token bytes at beginning
                        readTargetSourceChannelPosition = (FINALCRYPT_PLAIN_IEXT_AUTHENTICATION_TOKEN.length() * 2);
                    } else {
                        ui.status("â›” \"" + newTargetSourceFCPath.toString() + "\" - Cipher Failed : " + cipherSourceFCPath.toString() + "\r\n", true);
                        continue encryptTargetloop;
                    }
                }
            }
            // //		if (newTargetSourceFCPath.isEncrypted) // Target has Token, Decrypt New Format
            // //		{
            // //		    if (newTargetSourceFCPath.isDecryptable) // TargetSource Has Authenticated Token (Decryptable)
            // //		    {
            // //			fileStatusLine = "🔓 \"" + targetDestinPath.toString() + "\" ";
            // //			ui.status("🔓 \"" + targetDestinPath.toString() + "\" ", false);
            // //			readTargetSourceChannelPosition = (FINALCRYPT_PLAIN_IEXT_AUTHENTICATION_TOKEN.length() * 2); // Decrypt skipping Token bytes at beginning
            // //		    }
            // //		    else
            // //		    {
            // //			ui.status("â›” \"" + newTargetSourceFCPath.toString() + "\" - Cipher Failed : " + cipherSourceFCPath.toString() + "\r\n", true);
            // //			continue encryptTargetloop;
            // //		    }
            // //		}
            // else // Target has NO Token
            // {
            // if ( ! newTargetSourceFCPath.path.getFileName().toString().endsWith(bit_extension) ) // Target has No Token and no ".bit" extension, so add a Token at the beginning of targetDestinPath
            // {
            // ui.status(		"🔒 \"" + targetDestinPath.toString() + "\" ", false);
            // fileStatusLine =	"🔒 \"" + targetDestinPath.toString() + "\" ";
            // 
            // if ( ! dry )
            // {
            // ByteBuffer targetDestinTokenBuffer = ByteBuffer.allocate((FINALCRYPT_PLAIN_IEXT_AUTHENTICATION_TOKEN.length() * 2)); targetDestinTokenBuffer.clear();
            // try (final SeekableByteChannel writeTargetDestinChannel = Files.newByteChannel(targetDestinPath, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)))
            // {
            // targetDestinTokenBuffer = createTargetDestinToken(cipherSourceFCPath.path);
            // writeTargetDestChannelTransfered = writeTargetDestinChannel.write(targetDestinTokenBuffer); targetDestinTokenBuffer.flip();
            // writeTargetDestinChannel.close();
            // // wrteTargetDestinStat.addFileBytesProcessed(writeTargetDestChannelTransfered);
            // } catch (IOException ex) { ui.error("Error: Add Token writeTargetDestinChannel Abort Encrypting: " + targetDestinPath.toString() + " " + ex.getMessage() + "\r\n"); continue encryptTargetloop; }
            // }
            // 
            // readTargetSourceChannelPosition = 0; // Start reading targetSource from beginning (Encrypt)
            // }
            // else  // Target has No Token, but has a ".bit" extension
            // {
            // fileStatusLine = "🔓! \"" + targetDestinPath.toString()+ "\" "; // Decrypt Old Format
            // ui.status("🔓! \"" + targetDestinPath.toString() + "\" ", false);
            // readTargetSourceChannelPosition = 0;
            // }
            // }
            // ___________________________________________________________________________________________________________________________________________________________
            // 
            // Encryptor I/O Block
            ByteBuffer targetSourceBuffer = ByteBuffer.allocate(readTargetSourceBufferSize);
            targetSourceBuffer.clear();
            ByteBuffer cipherSourceBuffer = ByteBuffer.allocate(readTargetSourceBufferSize);
            cipherSourceBuffer.clear();
            ByteBuffer targetDestinBuffer = ByteBuffer.allocate(readTargetSourceBufferSize);
            targetDestinBuffer.clear();
            targetSourceEnded = false;
            long readTargetSourceChannelTransfered = 0;
            long readCipherSourceChannelPosition = 0;
            long readCipherSourceChannelTransfered = 0;
            long writeTargetDestChannelPosition = 0;
            writeTargetDestChannelTransfered = 0;
            long readTargetDestChannelPosition = 0;
            long readTargetDestChannelTransfered = 0;
            long writeTargetSourceChannelPosition = 0;
            long writeTargetSourceChannelTransfered = 0;
            // Get and set the stats
            // allDataStats.setFileBytesTotal(targetSourceSize);
            allDataStats.setFileBytesTotal(newTargetSourceFCPath.size);
            readTargetSourceStat.setFileBytesProcessed(0);
            readTargetSourceStat.setFileBytesTotal(newTargetSourceFCPath.size);
            // readCipherSourceStat.setFileBytesProcessed(0);      readCipherSourceStat.setFileBytesTotal(filesize);
            // wrteTargetDestinStat.setFileBytesProcessed(0);      wrteTargetDestinStat.setFileBytesTotal(filesize);
            // readTargetDestinStat.setFileBytesProcessed(0);      readTargetDestinStat.setFileBytesTotal(filesize);
            wrteTargetSourceStat.setFileBytesProcessed(0);
            wrteTargetSourceStat.setFileBytesTotal(newTargetSourceFCPath.size);
            // Open and close files after every bufferrun. Interrupted file I/O works much faster than uninterrupted I/O encryption
            while ((!targetSourceEnded) && (!dry)) {
                if (stopPending) {
                    // Delete broken outputFile and keep original
                    try {
                        Files.deleteIfExists(targetDestinPath);
                    } catch (IOException ex) {
                        ui.error("Files.deleteIfExists(targetDestinPath): " + ex.getMessage() + "\r\n");
                    }
                    targetSourceEnded = true;
                    ui.status("\r\n", true);
                    break encryptTargetloop;
                }
                // open targetSourcePath
                // allFilesStats.setFilesStartNanoTime();
                readTargetSourceStat.setFileStartEpoch();
                try (final SeekableByteChannel readTargetSourceChannel = Files.newByteChannel(newTargetSourceFCPath.path, EnumSet.of(StandardOpenOption.READ))) {
                    // Fill up inputFileBuffer
                    readTargetSourceChannel.position(readTargetSourceChannelPosition);
                    readTargetSourceChannelTransfered = readTargetSourceChannel.read(targetSourceBuffer);
                    targetSourceBuffer.flip();
                    readTargetSourceChannelPosition += readTargetSourceChannelTransfered;
                    // Buffer.limit = remainder from current position to end
                    if ((readTargetSourceChannelTransfered == -1) || (targetSourceBuffer.limit() < readTargetSourceBufferSize)) {
                        targetSourceEnded = true;
                    }
                    readTargetSourceChannel.close();
                    readTargetSourceStat.setFileEndEpoch();
                    readTargetSourceStat.clock();
                    readTargetSourceStat.addFileBytesProcessed(readTargetSourceChannelTransfered / 2);
                    allDataStats.addAllDataBytesProcessed("rd src", readTargetSourceChannelTransfered / 2);
                } catch (IOException ex) {
                    ui.error("readTargetSourceChannel = Files.newByteChannel(..) " + ex.getMessage() + "\r\n");
                    continue encryptTargetloop;
                }
                if (readTargetSourceChannelTransfered != -1) {
                    // readCipherSourceStat.setFileStartEpoch();
                    try (final SeekableByteChannel readCipherSourceChannel = Files.newByteChannel(cipherSourceFCPath.path, EnumSet.of(StandardOpenOption.READ))) {
                        // Fill up cipherFileBuffer
                        readCipherSourceChannel.position(readCipherSourceChannelPosition);
                        readCipherSourceChannelTransfered = readCipherSourceChannel.read(cipherSourceBuffer);
                        readCipherSourceChannelPosition += readCipherSourceChannelTransfered;
                        if (readCipherSourceChannelTransfered < readCipherSourceBufferSize) {
                            readCipherSourceChannelPosition = 0;
                            readCipherSourceChannel.position(0);
                            readCipherSourceChannelTransfered += readCipherSourceChannel.read(cipherSourceBuffer);
                            readCipherSourceChannelPosition += readCipherSourceChannelTransfered;
                        }
                        cipherSourceBuffer.flip();
                        readCipherSourceChannel.close();
                    // readCipherSourceStat.setFileEndEpoch(); readCipherSourceStat.clock();
                    // readCipherSourceStat.addFileBytesProcessed(readCipherSourceChannelTransfered);
                    } catch (IOException ex) {
                        ui.error("readCipherSourceChannel = Files.newByteChannel(..) " + ex.getMessage() + "\r\n");
                        continue encryptTargetloop;
                    }
                    // wrteTargetDestinStat.setFileStartEpoch();
                    try (final SeekableByteChannel writeTargetDestinChannel = Files.newByteChannel(targetDestinPath, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC))) {
                        // Encrypt inputBuffer and fill up outputBuffer
                        targetDestinBuffer = encryptBuffer(targetSourceBuffer, cipherSourceBuffer);
                        writeTargetDestChannelTransfered = writeTargetDestinChannel.write(targetDestinBuffer);
                        targetDestinBuffer.flip();
                        writeTargetDestChannelPosition += writeTargetDestChannelTransfered;
                        if (txt) {
                            logByteBuffer("DB", targetSourceBuffer);
                            logByteBuffer("CB", cipherSourceBuffer);
                            logByteBuffer("OB", targetDestinBuffer);
                        }
                        writeTargetDestinChannel.close();
                    // wrteTargetDestinStat.setFileEndEpoch(); wrteTargetDestinStat.clock();
                    // wrteTargetDestinStat.addFileBytesProcessed(writeTargetDestChannelTransfered);
                    } catch (IOException ex) {
                        ui.error("writeTargetDestinChannel = Files.newByteChannel(..) " + ex.getMessage() + "\r\n");
                        continue encryptTargetloop;
                    }
                // ui.log("writeTargetDestChannelTransfered: " + writeTargetDestChannelTransfered + " targetDestinBuffer.limit(): " + Integer.toString(targetDestinBuffer.limit()) + "\r\n");
                }
                targetDestinBuffer.clear();
                targetSourceBuffer.clear();
                cipherSourceBuffer.clear();
            }
            if (!dry) {
                attributeViewloop: for (// acl basic owner user dos
                String view : // acl basic owner user dos
                newTargetSourceFCPath.path.getFileSystem().supportedFileAttributeViews()) {
                    // ui.println(view);
                    if (view.toLowerCase().equals("basic")) {
                        try {
                            BasicFileAttributes basicAttributes = null;
                            basicAttributes = Files.readAttributes(newTargetSourceFCPath.path, BasicFileAttributes.class);
                            try {
                                Files.setAttribute(targetDestinPath, "basic:creationTime", basicAttributes.creationTime());
                                Files.setAttribute(targetDestinPath, "basic:lastModifiedTime", basicAttributes.lastModifiedTime());
                                Files.setAttribute(targetDestinPath, "basic:lastAccessTime", basicAttributes.lastAccessTime());
                            } catch (IOException ex) {
                                ui.error("Error: Set Basic Attributes: " + ex.getMessage() + "\r\n");
                            }
                        } catch (IOException ex) {
                            ui.error("Error: basicAttributes = Files.readAttributes(..): " + ex.getMessage());
                        }
                    } else if (view.toLowerCase().equals("dos")) {
                        try {
                            DosFileAttributes msdosAttributes = null;
                            msdosAttributes = Files.readAttributes(newTargetSourceFCPath.path, DosFileAttributes.class);
                            try {
                                Files.setAttribute(targetDestinPath, "basic:lastModifiedTime", msdosAttributes.lastModifiedTime());
                                Files.setAttribute(targetDestinPath, "dos:hidden", msdosAttributes.isHidden());
                                Files.setAttribute(targetDestinPath, "dos:system", msdosAttributes.isSystem());
                                Files.setAttribute(targetDestinPath, "dos:readonly", msdosAttributes.isReadOnly());
                                Files.setAttribute(targetDestinPath, "dos:archive", msdosAttributes.isArchive());
                            } catch (IOException ex) {
                                ui.error("Error: Set DOS Attributes: " + ex.getMessage() + "\r\n");
                            }
                        } catch (IOException ex) {
                            ui.error("Error: msdosAttributes = Files.readAttributes(..): " + ex.getMessage());
                        }
                    } else if (view.toLowerCase().equals("posix")) {
                        PosixFileAttributes posixAttributes = null;
                        try {
                            posixAttributes = Files.readAttributes(newTargetSourceFCPath.path, PosixFileAttributes.class);
                            try {
                                Files.setAttribute(targetDestinPath, "posix:owner", posixAttributes.owner());
                                Files.setAttribute(targetDestinPath, "posix:group", posixAttributes.group());
                                Files.setPosixFilePermissions(targetDestinPath, posixAttributes.permissions());
                                Files.setLastModifiedTime(targetDestinPath, posixAttributes.lastModifiedTime());
                            } catch (IOException ex) {
                                ui.error("Error: Set POSIX Attributes: " + ex.getMessage() + "\r\n");
                            }
                        } catch (IOException ex) {
                            ui.error("Error: posixAttributes = Files.readAttributes(..): " + ex.getMessage());
                        }
                    }
                }
            // End attributeViewloop // End attributeViewloop
            }
            // End ! dry
            // ==================================================================================================================================================================
            // Counting encrypting and shredding for the average throughtput performance
            // Shredding process
            // 🌊🗑
            ui.status("🗑 \"" + newTargetSourceFCPath.path.toAbsolutePath() + "\" ", false);
            long targetDestinSize = 0;
            double targetDiffFactor = 1;
            if (!dry) {
                // isValidFile(UI ui, String caller,        Path path, boolean device, long minSize, boolean symlink, boolean writable, boolean report)
                if (Validate.isValidFile(ui, "", targetDestinPath, false, 1, false, false, true)) {
                    try {
                        targetDestinSize = Files.size(targetDestinPath);
                        targetDiffFactor = newTargetSourceFCPath.size / targetDestinSize;
                    } catch (IOException ex) {
                        ui.error("Error: Files.size(targetDestinPath); " + ex.getMessage() + "\r\n");
                    }
                } else
                    readTargetSourceChannelPosition = 0;
                readTargetSourceChannelTransfered = 0;
                readCipherSourceChannelPosition = 0;
                readCipherSourceChannelTransfered = 0;
                writeTargetDestChannelPosition = 0;
                targetSourceBuffer = ByteBuffer.allocate(readTargetSourceBufferSize);
                targetSourceBuffer.clear();
                cipherSourceBuffer = ByteBuffer.allocate(readCipherSourceBufferSize);
                cipherSourceBuffer.clear();
                targetDestinBuffer = ByteBuffer.allocate(wrteTargetDestinBufferSize);
                targetDestinBuffer.clear();
                boolean targetDestinEnded = false;
                shredloop: while (!targetDestinEnded) {
                    while (pausing) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                    }
                    if (stopPending) {
                        targetDestinEnded = true;
                        break shredloop;
                    }
                    // readTargetDestinStat.setFileStartEpoch();
                    try (final SeekableByteChannel readTargetDestinChannel = Files.newByteChannel(targetDestinPath, EnumSet.of(StandardOpenOption.READ))) {
                        readTargetDestinChannel.position(readTargetDestChannelPosition);
                        readTargetDestChannelTransfered = readTargetDestinChannel.read(targetDestinBuffer);
                        targetDestinBuffer.flip();
                        readTargetDestChannelPosition += readTargetDestChannelTransfered;
                        if ((readTargetDestChannelTransfered < 1)) {
                            targetDestinEnded = true;
                        }
                        readTargetDestinChannel.close();
                    } catch (IOException ex) {
                        ui.error("readTargetDestinChannel = Files.newByteChannel(..) " + ex.getMessage() + "\r\n");
                        continue encryptTargetloop;
                    }
                    // if ( readTargetDestChannelTransfered < 1 )
                    if (targetDestinBuffer.limit() > 0) {
                        wrteTargetSourceStat.setFileStartEpoch();
                        try (final SeekableByteChannel writeTargetSourceChannel = Files.newByteChannel(newTargetSourceFCPath.path, EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.SYNC))) {
                            // Fill up inputFileBuffer
                            writeTargetSourceChannel.position(writeTargetSourceChannelPosition);
                            writeTargetSourceChannelTransfered = writeTargetSourceChannel.write(targetDestinBuffer);
                            targetSourceBuffer.flip();
                            writeTargetSourceChannelPosition += writeTargetSourceChannelTransfered;
                            if ((writeTargetSourceChannelTransfered < 1)) {
                                targetSourceEnded = true;
                            }
                            writeTargetSourceChannel.close();
                            wrteTargetSourceStat.setFileEndEpoch();
                            wrteTargetSourceStat.clock();
                            wrteTargetSourceStat.addFileBytesProcessed(writeTargetSourceChannelTransfered / 2);
                            allDataStats.addAllDataBytesProcessed("wr src", writeTargetSourceChannelTransfered / 2);
                        // if ( targetDiffFactor < 1 )
                        // { allDataStats.addAllDataBytesProcessed("wr src", writeTargetSourceChannelTransfered * Math.abs((long)targetDiffFactor)); } else
                        // { allDataStats.addAllDataBytesProcessed("wr src", writeTargetSourceChannelTransfered / Math.abs((long)targetDiffFactor)); }
                        } catch (IOException ex) {
                            ui.error("writeTargetSourceChannel = Files.newByteChannel(..) " + ex.getMessage() + "\r\n");
                            continue encryptTargetloop;
                        }
                    // ui.log("writeTargetSourceChannelTransfered: " + writeTargetSourceChannelTransfered + " targetDestinBuffer.limit(): " + Integer.toString(targetDestinBuffer.limit()) + "\r\n");
                    }
                    targetDestinBuffer.clear();
                    targetSourceBuffer.clear();
                    cipherSourceBuffer.clear();
                }
                // FILE STATUS
                if (verbose) {
                    fileStatusLine += "- Crypt: rd(" + readTargetSourceStat.getFileBytesThroughPut() + ") -> ";
                    // fileStatusLine += "rd(" +           readCipherSourceStat.getFileBytesThroughPut() + ") -> ";
                    // fileStatusLine += "wr(" +           wrteTargetDestinStat.getFileBytesThroughPut() + ") ";
                    // fileStatusLine += "- Shred: rd(" +  readTargetDestinStat.getFileBytesThroughPut() + ")";
                    fileStatusLine += "wr(" + wrteTargetSourceStat.getFileBytesThroughPut() + ") ";
                }
            }
            // End ! dry
            fileStatusLine += allDataStats.getAllDataBytesProgressPercentage();
            ui.log(fileStatusLine);
            allDataStats.addFilesProcessed(1);
            if (print) {
                ui.log(" ----------------------------------------------------------------------\r\n");
            }
            // Delete the original
            if (!dry) {
                if ((newTargetSourceFCPath.size != 0) && (targetDestinSize != 0) && (Math.abs(newTargetSourceFCPath.size - targetDestinSize) == (FINALCRYPT_PLAIN_IEXT_AUTHENTICATION_TOKEN.length()) * 2) || (newTargetSourceFCPath.size == targetDestinSize)) {
                    try {
                        Files.deleteIfExists(newTargetSourceFCPath.path);
                    } catch (IOException ex) {
                        ui.error("Files.deleteIfExists(inputFilePath): " + ex.getMessage() + "\r\n");
                        continue encryptTargetloop;
                    }
                }
            }
        }
        // else { ui.error(targetSourcePath.toAbsolutePath() + " ignoring:   " + cipherSourcePath.toAbsolutePath() + " (is cipher!)\r\n"); }
        // getFCPath(UI ui, String caller,	    Path path, boolean isCipher,		 Path cipherPath, boolean report)
        newTargetSourceFCPath = Validate.getFCPath(ui, "", targetDestinPath, false, cipherSourceFCPath.path, verbose);
        if (newTargetSourceFCPath.isEncrypted) {
            newTargetSourceFCPath.isNewEncrypted = true;
        } else {
            newTargetSourceFCPath.isNewDecrypted = true;
        }
        targetSourcePathList.updateStat(oldTargetSourceFCPath, newTargetSourceFCPath);
        ui.fileProgress();
    }
    // Encrypt Files Loop // Encrypt Files Loop
    allDataStats.setAllDataEndNanoTime();
    allDataStats.clock();
    // It breaks in the middle of encrypting, so the encryption summery needs to begin on a new line
    if (stopPending) {
        ui.status("\r\n", false);
        stopPending = false;
    }
    // Print the stats
    ui.status(allDataStats.getEndSummary("En/Decrypting"), true);
    updateProgressTaskTimer.cancel();
    updateProgressTaskTimer.purge();
    // updateProgressTimeline.stop();
    ui.processFinished();
}
Also used : Path(java.nio.file.Path) DosFileAttributes(java.nio.file.attribute.DosFileAttributes) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) SeekableByteChannel(java.nio.channels.SeekableByteChannel) TimerTask(java.util.TimerTask) Iterator(java.util.Iterator) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 19 with PosixFileAttributes

use of java.nio.file.attribute.PosixFileAttributes in project cryptofs by cryptomator.

the class CryptoPosixFileAttributeViewTest method testReadAttributesUsesProvider.

@Test
public void testReadAttributesUsesProvider() throws IOException {
    PosixFileAttributes expectedAttributes = mock(PosixFileAttributes.class);
    when(fileAttributeProvider.readAttributes(path, PosixFileAttributes.class)).thenReturn(expectedAttributes);
    PosixFileAttributes result = inTest.readAttributes();
    assertThat(result, is(expectedAttributes));
}
Also used : PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) Test(org.junit.Test)

Example 20 with PosixFileAttributes

use of java.nio.file.attribute.PosixFileAttributes in project cryptofs by cryptomator.

the class CryptoFileAttributeProviderTest method setup.

@Before
public void setup() throws IOException {
    cryptor = Mockito.mock(Cryptor.class);
    ciphertextFilePath = Mockito.mock(Path.class);
    FileSystem fs = Mockito.mock(FileSystem.class);
    Mockito.when(ciphertextFilePath.getFileSystem()).thenReturn(fs);
    FileSystemProvider provider = Mockito.mock(FileSystemProvider.class);
    Mockito.when(fs.provider()).thenReturn(provider);
    BasicFileAttributes basicAttr = Mockito.mock(BasicFileAttributes.class);
    PosixFileAttributes posixAttr = Mockito.mock(PosixFileAttributes.class);
    DosFileAttributes dosAttr = Mockito.mock(DosFileAttributes.class);
    Mockito.when(provider.readAttributes(Mockito.same(ciphertextFilePath), Mockito.same(BasicFileAttributes.class), Mockito.any())).thenReturn(basicAttr);
    Mockito.when(provider.readAttributes(Mockito.same(ciphertextFilePath), Mockito.same(PosixFileAttributes.class), Mockito.any())).thenReturn(posixAttr);
    Mockito.when(provider.readAttributes(Mockito.same(ciphertextFilePath), Mockito.same(DosFileAttributes.class), Mockito.any())).thenReturn(dosAttr);
}
Also used : Path(java.nio.file.Path) Cryptor(org.cryptomator.cryptolib.api.Cryptor) FileSystemProvider(java.nio.file.spi.FileSystemProvider) DosFileAttributes(java.nio.file.attribute.DosFileAttributes) FileSystem(java.nio.file.FileSystem) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Before(org.junit.Before)

Aggregations

PosixFileAttributes (java.nio.file.attribute.PosixFileAttributes)37 Path (java.nio.file.Path)17 IOException (java.io.IOException)13 Test (org.junit.Test)13 PosixFileAttributeView (java.nio.file.attribute.PosixFileAttributeView)11 File (java.io.File)8 PosixFilePermission (java.nio.file.attribute.PosixFilePermission)8 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)6 FileTime (java.nio.file.attribute.FileTime)5 HashMap (java.util.HashMap)5 InputStream (java.io.InputStream)4 OutputStream (java.io.OutputStream)4 DosFileAttributes (java.nio.file.attribute.DosFileAttributes)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Set (java.util.Set)4 UfsDirectoryStatus (alluxio.underfs.UfsDirectoryStatus)3 UfsFileStatus (alluxio.underfs.UfsFileStatus)3 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableMap (com.google.common.collect.ImmutableMap)3