Sunday, September 26, 2010

Two way sync

Two way sync
This time I have attempted to solve another important task - Backup.

Everyone understands the importance of taking backup of personal files and it is difficult to find a program which does this job smartly. I googled and explored a few which don't suite my requirements, so I made a small attempt here to write a program myself than using third party tools.

As part of this, first I started with two way sync. This code generates the list of missed files in both directories by walking through and sync in both the ways.

The following code uses the power of new NIO2 from JDK7. To run this code you need JDK7


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.Map.Entry;
import static java.nio.file.FileVisitResult.*;
import static java.nio.file.StandardCopyOption.*;

public class AstuteSync {
    private final static Lock lock = new ReentrantLock();
    private static Map<String,String> diffList = new ConcurrentSkipListMap<String,String>();
    private final static String SOURCE = "/extra/movies";
    private final static String TARGET = "/extra/movies_back";
    static 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) {
            toList(dir);
            return CONTINUE;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            toList(file);
            return CONTINUE;
        }
        private void toList(Path file) {
            try {
                lock.lock();
                if(diffList.remove(file.toString().replace(head, "")) == null)
                      diffList.put(file.toString().replace(head, ""),file.toString());
                lock.unlock();
            } catch (Exception exc) { exc.printStackTrace(); }
        }
    }
    public static void printDiffList() {
        if (diffList.isEmpty()) {
            System.out.println("Both folders are in Sync.");
        } else {
            Iterator<String> ite = diffList.values().iterator();
            System.out.println("Folder Diff:");
            while (ite.hasNext()) System.out.println(ite.next());
        }
    }
    public static void sync() {
        Set<Entry<String,String>>entries = diffList.entrySet();
        for (Map.Entry<String,String>entry : entries) {
            try {
                Paths.get(entry.getValue()).copyTo(Paths.get(
                        (entry.getValue().startsWith(TARGET) ? SOURCE : TARGET) +
                        System.getProperty("file.separator") + entry.getKey()), COPY_ATTRIBUTES);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void main(String... arg) throws Exception {
        final Path source = Paths.get(SOURCE);
        final Path target = Paths.get(TARGET);
        if(!source.exists() || !target.exists()) throw new Exception("Path doesn't exists");
        new Thread(new Runnable(){ public void run() {
        Files.walkFileTree(source, new SyncFileVisitor(SOURCE));}}).start();
        new Thread(new Runnable() {public void run() {
        Files.walkFileTree(target, new SyncFileVisitor(TARGET));}}).start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override   public void run() {
                printDiffList();
                if (!diffList.isEmpty())  sync();
            }
        });
    }
}
$ java AstuteSync
/extra/movies/k.txt
/extra/movies/p.txt
/extra/movies_back/test.t

$java AstuteSync
Both folders are in Sync.

Sunday, July 25, 2010

Shuffle my songs

I have recently hit upon a limitation with my car MP3 player playing songs from my USB. It doesn’t have a SHUFFLE option :( and I had to always listen in the same order again and again.

It might sound obvious and simple to manually rename the files and sort, but if you have huge list of songs under multiple folders, you would certainly require a smart program which does this job for you.

This program uses the new NIO.2 from JDK7. It recursively goes through all the subfolders and search for .mp3/.MP3 files, copy to target folder after renaming. Please use latest JDK 7 to run this program.

More about NIO.2 http://java.sun.com/developer/technicalArticles/javase/nio/

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= "/TEMP";
private static final String TARGET= "/TEST/";
private static void copyThisFile(Path file) throws IOException {
Path targetPath = Paths.get(TARGET+UUID.randomUUID().toString().replaceAll("-","")+".mp3");
file.copyTo(targetPath, REPLACE_EXISTING);
System.out.println("Copied " + file.toString() + " to " + targetPath.toString());
}

static class Mp3FileVisitor extends SimpleFileVisitor<Path> {

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
try {
if(file.getName().toString().lastIndexOf(".mp3") >=0
file.getName().toString().lastIndexOf(".MP3") >=0)
copyThisFile(file);
} catch (Exception exc) { exc.printStackTrace(); }
return FileVisitResult.CONTINUE;
}
}
public static void main(String... arg) {
final Path path = Paths.get(SOURCE);
Files.walkFileTree(path, new Mp3FileVisitor());
}
}

While storing back in your USB/SD/’Memory device’ please sort. As some parameter needs to supply like source and target, don’t try this program on your master list. I suggest taking a backup of the files before running this utility program against it.

$javac ShuffleMp3

$ java ShuffleMp3

Copied /TEMP/English/Old/OldTest.mp3 to /TEST/9ad4282b-c775-4508-8133-74f45b8a0197.mp3

Copied /TEMP/English/TEST.mp3 to /TEST/fc03dbdb-04f2-4eb8-98f8-ff50b0668411.mp3

Copied /TEMP/Telugu/TEST1.mp3 to /TEST/8b97aa92-7a17-4e8d-926b-cf3ff4344f6c.mp3