se.hakanostrom.traveldiary.DEPRECATED.Internet.java Source code

Java tutorial

Introduction

Here is the source code for se.hakanostrom.traveldiary.DEPRECATED.Internet.java

Source

/*******************************************************************************
 * Copyright 2012 Hkan strm
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package se.hakanostrom.traveldiary.DEPRECATED;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ProcessingInstruction;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * This class is static
 * 
 * @author Hkan strm
 */
public class Internet {

    private Context mContext;
    private final String FILE_NAME = "traveldiary.xml";

    /**
     * Constructor setting the application context
     * 
     * @param _c
     *            the application context
     */
    public Internet(Context _c) {
        mContext = _c;
    }

    /**
     * Get the public link (full url)
     * 
     * @return String containing the url
     */
    public String getPublicLink() {
        return InternetConstants.WEB_URL + "/?id=" + readHash();
    }

    /**
     * Upload the xml and images to the web. Do so by starting different threads.
     * 
     * @throws IOException
     *             It could not be converted and/or uploaded
     * @throws ParserConfigurationException
     * @throws TransformerException
     */
    public void uploadToWeb() throws IOException, ParserConfigurationException, TransformerException {
        // Get contents from database to an xml
        // Traveldiary_DB.exportToFile(FILE_NAME, mContext);
        new WriteXMLFile().export(FILE_NAME);

        // Upload everything in folder that does not already exists on server
        // (force upload the xml)
        new UploadThread().execute(readHash());

    }

    // Read the hash from shared prefs, creat it if it is not present
    private long readHash() {

        SharedPreferences settings = mContext.getSharedPreferences("InternetPreferences", 0);
        SharedPreferences.Editor prefEditor = settings.edit();

        // If it does not exists i shared prefs?
        if (!settings.contains("hash")) {

            // Create and write it
            prefEditor.putLong("hash", System.currentTimeMillis());
            // prefEditor.putLong("hash", 42);
            prefEditor.commit();
        }

        // Fetch and return it
        return settings.getLong("hash", 0);

    }

    // Start a new thread and upload the named file
    private class UploadThread extends AsyncTask<Long, String, String> {

        @Override
        protected String doInBackground(Long... params) {

            // Create and open ftp connection
            FTPClient ftp = new FTPClient();

            try {

                ftp.connect(InternetConstants.FTP_HOST, InternetConstants.PORT);

                if (ftp.login(InternetConstants.USERNAME, InternetConstants.PASSWORD)) {
                    ftp.enterLocalPassiveMode(); // important

                    // Create directory remotely if it does not exists ???
                    ftp.mkd("www-access/" + params[0]);

                    // Upload xml

                    // open it (sandbox)
                    InputStream in = mContext.openFileInput(FILE_NAME);

                    boolean result = ftp.storeFile("/www-access/" + params[0] + "/" + FILE_NAME, in);
                    in.close();
                    if (result)
                        Log.i("ip2012", "upload xml: succeeded");
                    else
                        Log.e("ip2012", "upload xml: fail");

                }

                publishProgress("Finished the xml. Moving on with images ...");

                // Create folder "images" if neccesary
                boolean notExists = true;

                for (FTPFile f : ftp.listDirectories("/www-access/" + params[0])) {
                    if (f.getName().equals("images"))
                        notExists = false;
                }

                if (notExists) {
                    Log.i("ip2012", "folder \"images\" does not exist. Must be created");
                    ftp.makeDirectory("/www-access/" + params[0] + "/images");
                }

                // Check what is missing on the server
                // Upload missing pieces in loop

                // Get file list from sd
                File directory = new File("/sdcard/traveldiary/images");

                try {
                    for (File f : directory.listFiles()) {
                        Log.v("ip2012", "Processing file: " + f.getName());

                        // Does it exist on server

                        // If the file can be found both local and on ftp than dont upload
                        boolean foundIt = false;

                        for (FTPFile ftpF : ftp.listFiles("/www-access/" + params[0] + "/images/")) {

                            // Log.v("ip2012", ftpF.getName()+ " exists on FTP-server");

                            if (ftpF.getName().equals(f.getName())) {
                                Log.v("ip2012",
                                        "This file (" + f.getName() + ") exists on FTP-server. No need to upload.");
                                foundIt = true;
                                break;
                            }
                        }

                        if (!foundIt) {

                            // open it
                            InputStream in = new FileInputStream(f);
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            boolean result = ftp.storeFile("/www-access/" + params[0] + "/images/" + f.getName(),
                                    in);
                            in.close();

                            if (result) {
                                Log.v("ip2012", "upload succeeded");
                                publishProgress(f.getName() + " uploaded");
                            } else
                                Log.v("ip2012", "upload fail");
                        }
                    }
                } catch (NullPointerException e) {
                    publishProgress("No files found");
                    Log.e("ip2012", "No files found");
                    e.printStackTrace();
                }

            } catch (ConnectException e) {
                Log.e("IP2012", "No network!!");
                return "ftp failed";
            } catch (Exception e) {
                Log.e("IP2012", "Upload failed", e);
                return "ftp failed";
            }

            // Close ftp connection
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                Log.e("IP2012", "Problem logging out/disconnect", e);
            }

            return "Done ...";

        }

        @Override
        protected void onProgressUpdate(String... values) {
            // notification about successful upload (via Toast or statusbar)
            Log.i("ip2012", values[0]);
            Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            // Incorrect message !!!
            Toast.makeText(mContext, "Completed upload succesfully!", Toast.LENGTH_SHORT).show();
            super.onPostExecute(result);
        }

    }

    // Inner class used for writing database to XML
    private class WriteXMLFile {

        private TravelDiaryDatabaseHelper mDatabase;
        private SQLiteDatabase db;
        private Document doc;

        // The constructor
        public WriteXMLFile() {
            mDatabase = new TravelDiaryDatabaseHelper(mContext);
        }

        public void export(final String FILE_NAME)
                throws IOException, ParserConfigurationException, TransformerException {

            db = mDatabase.getWritableDatabase();

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            final String SQL = "SELECT * FROM trip ORDER BY id DESC";

            // Root element
            doc = docBuilder.newDocument();

            // Append stylesheet xsl
            ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet",
                    " type=\"text/xsl\" href=\"../template.xsl\"");
            doc.appendChild(pi);

            Element rootElement = doc.createElement("traveldiary");
            doc.appendChild(rootElement);

            // For the future. Maybe someone wants to import database/xml
            rootElement.setAttribute("id", readHash() + "");

            // get the tables
            Cursor cursor = db.rawQuery(SQL, new String[0]);

            if (cursor.moveToFirst()) {
                do {
                    // Create element (node)
                    Element trip = doc.createElement("trip");
                    rootElement.appendChild(trip);

                    // Set attribute "id"
                    trip.setAttribute("id", cursor.getString(cursor.getColumnIndex("_id")));

                    // Set attribute "actice
                    trip.setAttribute("active", "" + cursor.getString(cursor.getColumnIndex("active")));

                    // The name
                    Element name = doc.createElement("name");
                    name.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("name"))));
                    trip.appendChild(name);

                    // The note_text
                    Element note_text = doc.createElement("note_text");
                    note_text.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("noteText"))));
                    trip.appendChild(note_text);

                    // The start_date
                    Element start_date = doc.createElement("start_date");
                    start_date
                            .appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("startDate"))));
                    trip.appendChild(start_date);

                    // The end_date
                    Element end_date = doc.createElement("end_date");
                    end_date.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("endDate"))));
                    trip.appendChild(end_date);

                    // The place (if any)
                    exportPlace(trip);

                } while (cursor.moveToNext());
            }

            // Close the cursor
            cursor.close();

            // Write contents to XML file
            // Use internal storage (sandbox)

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);

            // new File("/data/data/se.hakanostrom.ip2012/files/", FILE_NAME).createNewFile();
            // Generates FNFException ??? bug maybe?
            // StreamResult result = new StreamResult(new FileOutputStream("/data/data/se.hakanostrom.ip2012/files/" + FILE_NAME));

            StreamResult result = new StreamResult(mContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE));

            transformer.transform(source, result);

            // Close database
            mDatabase.close();

            Log.i("ip2012", "exporting database complete");
        }

        private void exportPlace(Element element) {
            final String SQL = "SELECT * FROM Place WHERE Trip_id=\"" + element.getAttribute("id") + "\"";

            Element place;

            // get the tables
            Cursor cursor = db.rawQuery(SQL, new String[0]);

            if (cursor.moveToFirst()) {
                do {
                    // Create element (node)
                    place = doc.createElement("place");

                    // Set attribute "id"
                    place.setAttribute("id", cursor.getString(cursor.getColumnIndex("ID")));

                    // The name
                    Element name = doc.createElement("name");
                    name.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Name"))));
                    place.appendChild(name);

                    // The lat
                    Element lat = doc.createElement("lat");
                    lat.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Lat"))));
                    place.appendChild(lat);

                    // The lon
                    Element lon = doc.createElement("lon");
                    lon.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Lon"))));
                    place.appendChild(lon);

                    // The note_text
                    Element note_text = doc.createElement("note_text");
                    note_text.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Note_text"))));
                    place.appendChild(note_text);

                    // The date
                    Element date = doc.createElement("date");
                    date.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Date"))));
                    place.appendChild(date);

                    // The image (if any)
                    exportImage(place);

                    // Append it on parent
                    element.appendChild(place);

                } while (cursor.moveToNext());
            }

            // Close the cursor
            cursor.close();
        }

        private void exportImage(Element element) {
            final String SQL = "SELECT * FROM Image WHERE Place_id=\"" + element.getAttribute("id") + "\"";

            Element image;

            // get the tables
            Cursor cursor = db.rawQuery(SQL, new String[0]);

            if (cursor.moveToFirst()) {
                do {
                    // Create element (node)
                    image = doc.createElement("image");

                    // Set attribute "id"
                    image.setAttribute("id", cursor.getString(cursor.getColumnIndex("ID")));

                    // The filename
                    Element filename = doc.createElement("filename");
                    filename.appendChild(
                            doc.createTextNode("images/" + cursor.getString(cursor.getColumnIndex("Filename"))));
                    image.appendChild(filename);

                    // The note_text
                    Element note_text = doc.createElement("note_text");
                    note_text.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Note_text"))));
                    image.appendChild(note_text);

                    // The date
                    Element date = doc.createElement("date");
                    date.appendChild(doc.createTextNode(cursor.getString(cursor.getColumnIndex("Date"))));
                    image.appendChild(date);

                    // Append it on parent
                    element.appendChild(image);

                } while (cursor.moveToNext());
            }

            // Close the cursor
            cursor.close();

        }

    }
}