package com.kryptnostic.api.v1.client;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.kryptnostic.kodex.v1.storage.DataStore;

/**
 * A simple implementation of the client datastore. The keys are used to generate filenames.
 * 
 * @author Nick Hewitt &lt;nick@kryptnostic.com&gt;
 *
 */
public class FileStore implements DataStore {
    private final Path rootDirectory;
    private static HashFunction hf = Hashing.murmur3_128();

    public FileStore(String name) {
        this.rootDirectory = Paths.get(System.getProperty("user.home"), name);
        File dir = rootDirectory.toFile();
        dir.mkdir();
    }

    @Override
    public byte[] get(byte[] key) throws IOException {
        Path keyPath = keyToPath(key);
        try {
            byte[] data = Files.readAllBytes(keyPath);
            return data;
        } catch (NoSuchFileException e) {
            return null;
        }
    }

    @Override
    public void put(byte[] key, byte[] value) throws IOException {
        Path keyPath;
        keyPath = keyToPath(key);
        Files.write(keyPath, value);
    }

    private Path keyToPath(byte[] key) {
        Long longEncodedKey = hf.hashBytes(key).asLong();
        return rootDirectory.resolve(longEncodedKey.toString());
    }

}

@@ -85,133 +85,8 @@
 ion;
-%0Aimport java.nio.file.Files;%0Aimport java.nio.file.NoSuchFileException;%0Aimport java.nio.file.Path;%0Aimport java.nio.file.Paths;
 %0A%0Aim
@@ -166,16 +166,51 @@
 ashing;%0A
+import com.google.common.io.Files;%0A
 import c
@@ -477,20 +477,20 @@
 e final 
-Path
+File
  rootDir
@@ -627,17 +627,16 @@
 y = 
-Paths.get
+new File
 (Sys
@@ -684,19 +684,13 @@
     
-File dir = 
+this.
 root
@@ -703,30 +703,8 @@
 ory.
-toFile();%0A        dir.
 mkdi
@@ -796,28 +796,28 @@
     
-Path keyPath
+File keyFile
  = keyTo
 Path
@@ -804,36 +804,36 @@
  keyFile = keyTo
-Path
+File
 (key);%0A        t
@@ -835,11 +835,29 @@
     
-try
+if (keyFile.isFile())
  %7B%0A 
@@ -891,28 +891,27 @@
 les.
-readAllBytes(keyPath
+toByteArray(keyFile
 );%0A 
@@ -947,52 +947,17 @@
    %7D
- catch (NoSuchFileException e) %7B%0A   
+%0A
         
  ret
@@ -948,25 +948,24 @@
   %7D%0A        
- 
 return null;
@@ -965,26 +965,16 @@
 n null;%0A
-        %7D%0A
     %7D%0A%0A 
@@ -1065,45 +1065,28 @@
     
-Path keyPath;%0A        keyPath
+File keyFile
  = keyTo
 Path
@@ -1081,20 +1081,20 @@
  = keyTo
-Path
+File
 (key);%0A 
@@ -1116,21 +1116,21 @@
 ite(
-keyPath, valu
+value, keyFil
 e);%0A
@@ -1152,22 +1152,22 @@
 ate 
-Path
+File
  keyTo
-Path
+File
 (byt
@@ -1250,16 +1250,25 @@
  return 
+new File(
 rootDire
@@ -1276,17 +1276,10 @@
 tory
-.resolve(
+, 
 long

fix for Java 6