mydropbox.Client.java Source code

Java tutorial

Introduction

Here is the source code for mydropbox.Client.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mydropbox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import static org.apache.http.params.CoreProtocolPNames.USER_AGENT;
import org.apache.http.util.EntityUtils;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author lucas
 */
public class Client {
    private HttpClient httpClient;
    private String host;

    public Client(String host) {
        System.out.println("Starting client");
        this.host = host;
        initHttp();
    }

    private void initHttp() {
        try {
            httpClient = HttpClientBuilder.create().build();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private long getTimeStamp() throws IOException {
        long timestamp = 0;
        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader("./timestamp.mydropbox"));
            String line;
            while ((line = br.readLine()) != null) {
                timestamp = Long.parseLong(line, 10);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return timestamp;
    }

    private void setTimeStamp(long timestamp) throws IOException {
        try {
            PrintWriter writer = new PrintWriter("./timestamp.mydropbox", "UTF-8");
            writer.println(timestamp);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public long askForTimeStamp() {
        System.out.println("Asking cloud timestamp");
        long timestamp = 0;
        HttpPost httpPost = new HttpPost(this.host + "askfortimestamp");

        HttpResponse response;

        try {
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setHeader("MyDropBox", "MyDropBox");

            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            System.out.println(response.getStatusLine());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            return Long.parseLong(EntityUtils.toString(resEntity), 10);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }

    public Set<String> askForFileList() throws IOException {
        Set<String> fileList = new HashSet<String>();

        HttpPost httpPost = new HttpPost(this.host + "getfilelist");

        System.out.println("executing request " + httpPost.getRequestLine());
        HttpResponse response;

        try {
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setHeader("MyDropBox", "MyDropBox");

            response = httpClient.execute(httpPost);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                fileList.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileList;
    }

    public boolean sendFile(String fileName) throws IOException {
        int status = 0;
        Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis());
        long timestamp = temp_timestamp.getTime();
        File file = new File("./files/" + fileName);
        HttpPost httpPost = new HttpPost(this.host + "upload" + '/' + timestamp);

        MultipartEntity mpEntity = new MultipartEntity();

        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart(file.getName(), cbFile);

        httpPost.setEntity(mpEntity);
        System.out.println("executing request " + httpPost.getRequestLine());
        HttpResponse response;

        try {
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setHeader("MyDropBox", "MyDropBox");

            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            System.out.println(response.getStatusLine());
            status = response.getStatusLine().getStatusCode();
            System.out.println("Response Code : " + status);
            System.out.println(EntityUtils.toString(resEntity));

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            setTimeStamp(timestamp);
        }
        if (status >= 200 && status < 300)
            return true;
        else
            return false;
    }

    public boolean downloadFile(String fileName) {
        File file = new File("./files/" + fileName);

        HttpGet httpGet = new HttpGet(this.host + "download/" + fileName);
        httpGet.setHeader("User-Agent", USER_AGENT);
        httpGet.setHeader("MyDropBox", "MyDropBox");

        HttpResponse response;

        try {
            response = httpClient.execute(httpGet);
            HttpEntity fileEntity = response.getEntity();

            if (fileEntity != null)
                FileUtils.copyInputStreamToFile(fileEntity.getContent(), file);

        } catch (Exception ex) {
            return false;
        }
        httpGet.releaseConnection();
        return true;
    }

    public boolean deleteFile(String fileName) throws IOException {
        Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis());
        long timestamp = temp_timestamp.getTime();
        HttpGet httpGet = new HttpGet(this.host + "delete/" + fileName + '/' + timestamp);
        httpGet.setHeader("User-Agent", USER_AGENT);
        httpGet.setHeader("MyDropBox", "MyDropBox");

        HttpResponse response;

        try {
            response = httpClient.execute(httpGet);
            HttpEntity resEntity = response.getEntity();

            System.out.println(response.getStatusLine());
            int status = response.getStatusLine().getStatusCode();
            System.out.println("Response Code : " + status);
            System.out.println(EntityUtils.toString(resEntity));

            if (status >= 200 && status < 300) {
                httpGet.releaseConnection();
                return true;
            } else {
                httpGet.releaseConnection();
                return false;
            }
        } catch (Exception ex) {
            httpGet.releaseConnection();
            return false;
        } finally {
            setTimeStamp(timestamp);
        }
    }

    public void checkForChanges() throws IOException {
        long timestamp_current = getTimeStamp();
        long timestamp_cloud = askForTimeStamp();
        long timestampToSave;

        Set<String> fileList_cloud = new HashSet<String>();
        Set<String> fileList_local = new HashSet<String>();

        if (timestamp_current != timestamp_cloud) {
            timestampToSave = Long.max(timestamp_cloud, timestamp_current);

            fileList_cloud = askForFileList();

            File folder = new File("./files/");
            File[] listOfFiles = folder.listFiles();

            for (File f : listOfFiles) {
                if (f.isFile()) {
                    fileList_local.add(f.getName());
                }
            }

            if (timestamp_current < timestamp_cloud) {
                System.out.println("Cloud is ahead");
                //Files that need to be removed
                Set<String> toRemoveList = new HashSet<String>();
                toRemoveList.addAll(fileList_local);
                toRemoveList.removeAll(fileList_cloud);

                //Files that need to be downloaded
                Set<String> toTransferList = new HashSet<String>();
                toTransferList.addAll(fileList_cloud);
                toTransferList.removeAll(fileList_local);

                try {
                    File file;
                    for (String f : toRemoveList) {
                        file = new File("./files/" + f);
                        file.delete();
                    }

                    for (String f : toTransferList) {
                        downloadFile(f);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    setTimeStamp(timestampToSave);
                }
            } else {
                System.out.println("Client is ahead");
                //Files that need to be removed in the cloud
                Set<String> toRemoveList = new HashSet<String>();
                toRemoveList.addAll(fileList_cloud);
                toRemoveList.removeAll(fileList_local);

                //Files that need to be uploaded
                Set<String> toTransferList = new HashSet<String>();
                toTransferList.addAll(fileList_local);
                toTransferList.removeAll(fileList_cloud);

                try {
                    File file;
                    for (String f : toRemoveList) {
                        deleteFile(f);
                    }

                    for (String f : toTransferList) {
                        sendFile(f);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    setTimeStamp(timestampToSave);
                }
            }
        }
    }
}