Monday, May 16, 2011

JDK7 NIO.2 Change

JDK7 NIO.2 API change

My initial blog code ShuffelMP3 and AstuteSync will not work as some of JDK7 NIO.2 methods are refactored. The copy and exists methods have been moved to Files. I have updated my code and added some of JDK7 coin features. RED colored statement for recent NIO.2 JDK chnages.

========= ShuffleMP3 ==================

package javatrails;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.UUID;
import static java.nio.file.StandardCopyOption.*;

public class ShuffleMp3 {

    private static final String SOURCE = "/home/dhanvi/TEMP";
    private static final String TARGET = "/home/dhanvi/TEST";

    private static void copyThisFile(Path file)  {
        try {
            Path targetPath = Paths.get(TARGET + System.getProperty("file.separator")
                         + UUID.randomUUID().toString().replaceAll("-", "") + ".mp3");

            Files.copy(file,targetPath, REPLACE_EXISTING);
            System.out.println("Copied " + file.toString() + " to " + targetPath.toString());
        } catch (IOException | Exception ex) {
            ex.printStackTrace();
        }
    }

    static class Mp3FileVisitor extends SimpleFileVisitor<Path> {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {   
            if (file.toString().lastIndexOf(".mp3") >= 0  ||
                            file.toString().lastIndexOf(".MP3") >= 0)
                copyThisFile(file);
            return FileVisitResult.CONTINUE;
        }
    }

    public static void main(String... arg) {
        try {
            final Path path = Paths.get(SOURCE);
            if(!Files.exists(path))  throw new IllegalStateException("Sorry file doen't exists");
                Files.walkFileTree(path, new Mp3FileVisitor());
        } catch (@jdk7("Coin : Multi-catch and more precise rethrow") final IOException | IllegalStateException ex) {
            ex.printStackTrace();
        }
    }
}
  


========= AstuteSync ==================

package javatrails;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.*;
import static java.nio.file.FileVisitResult.*;
import static java.nio.file.StandardCopyOption.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AstuteSync {
    private final static Lock lock = new ReentrantLock();
    @jdk7("Coin : Improved type inference for generic instance creation (diamond)")
    private final Map<String,String> diffList = new ConcurrentSkipListMap<>();
    private class SyncFileVisitor extends SimpleFileVisitor<Path> {
        private String head;
        public SyncFileVisitor(String head) {
            this.head = head.endsWith(System.getProperty("file.separator"))
                             ? head.substring(0,head.length()-1) : head;
        }
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            toList(dir);
            return CONTINUE;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            toList(file);
            return CONTINUE;
        }
        private void toList(Path file) {
            lock.lock();
            try {
                if (diffList.remove(file.toString().replace(head, "")) == null) 
                    diffList.put(file.toString().replace(head, ""), file.toString());
            } finally {
                lock.unlock();
            }
        }
    }
    private void printDiffList() {
        if(diffList.isEmpty())
            System.out.println("Both folders are in Sync.");
        else {
            System.out.println("Folder Diff:");
            for(String s : diffList.values())  
            System.out.println(s);
        }
    }
    private void sync(final Path source, final Path target) {
        Set<Entry<String, String>> entries = diffList.entrySet();
        for(Map.Entry<String,String> entry : entries) {
            try {
                Path tmpSource = Paths.get(entry.getValue());
                Path tmpTarget = Paths.get(
                    (entry.getValue().startsWith(target.toString()) ? source.toString() : target.toString()) +
                System.getProperty("file.separator") + entry.getKey());
                Files.copy(tmpSource, tmpTarget, COPY_ATTRIBUTES);
            } catch (Exception ex) {ex.printStackTrace();}
        }
    }
    public void startSync(final String SOURCE, final String TARGET) {
        final Path source = Paths.get(SOURCE);
        final Path target = Paths.get(TARGET);
        if(!Files.exists(source) || !Files.exists(target))  
            throw new IllegalStateException("Sorry file doen't exists");
        new Thread(new Runnable() {public void run() {
            try {
                Files.walkFileTree(source, new SyncFileVisitor(SOURCE));
            } catch (IOException ex) {
                Logger.getLogger(AstuteSync.class.getName()).log(Level.SEVERE, null, ex);
            }
        }}).start();
        new Thread(new Runnable() {public void run() {
            try {
                Files.walkFileTree(target, new SyncFileVisitor(TARGET));
            } catch (IOException ex) {
                Logger.getLogger(AstuteSync.class.getName()).log(Level.SEVERE, null, ex);
            }
        }}).start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override public void run() {
            printDiffList();
            if(!diffList.isEmpty()) sync(source, target);
        }
        });
    }
    public static void main(String... arg)  {
        new AstuteSync().startSync("/home/dhanvi/TEMP", "/home/dhanvi/TEST");
    }
}
@interface jdk7 {
    String value();
}