Android Open Source - adkintun-mobile-browser File Handler






From Project

Back to project page adkintun-mobile-browser.

License

The source code is released under:

Apache License

If you think the Android project adkintun-mobile-browser listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
* Copyright 2013 NIC Chile Research Labs
* // w  w  w  .  ja va2s.co m
* 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 cl.niclabs.adkintunmobile.browser;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import cl.niclabs.adkintunmobile.crypto.AESEncrypter;
import cl.niclabs.adkintunmobile.crypto.RSAEncrypter;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Build.VERSION;
import android.util.Log;

/**
 * Clase encargada del manejo del archivo de datos almacenados.
 * 
 * @author Sebastin Pereira
 * 
 */
public class FileHandler{
  private static final String SEPARATOR = " | ";
  
  /**
   * Agrega al archivo una linea con los datos entregados como parametros
   * @param deviceID ID del dispositivo
   * @param time Hora en que se realiz la medicin
   * @param signalStrength Intensidad de la seal
   * @param cellID ID de la antena celular
   * @param protocol Protocolo (NetworkType)
   * @param carrier Compaia
   * @param interrupted Indica si el usuario interrumpi la carga de la URL
   * @param tld TLD de la URL
   * @param timeToLoad Tiempo que tom cargar la URL
   * @param bytesSent Cantidad de bytes enviados
   * @param bytesReceived Cantidad de bytes recibidos
   */
  public static void addEntry(String deviceID, long time, int signalStrength, String cellInfo,
      String subtype, String carrier, boolean interrupted, String tld, long timeToLoad,
      long bytesSent, long bytesReceived) {
    String filename = deviceID + "-browser.txt";
    try {
      File root = new File(Environment.getExternalStorageDirectory(), C.folder);
      File dataFile = new File(root, filename);
      
      if (!root.exists()) {
        root.mkdirs();
      }
      
      if (!dataFile.exists()) {
        if(!dataFile.createNewFile()){
          Log.e("AdkinBrowser", "IO Error: " + "Unable to create file");
          return;
        }
      }
      
      // Obtengo fecha
      String date = new SimpleDateFormat("dd/MM/yy").format(new Date(time));
      String timeOfDay = new SimpleDateFormat("HH:mm:ss").format(new Date(time));
      int version = VERSION.SDK_INT;
      String dBm = String.valueOf( (2*signalStrength) - 113);

      StringBuffer dataLine = new StringBuffer();
      dataLine.append(date + SEPARATOR);
      dataLine.append(timeOfDay + SEPARATOR);
      dataLine.append("D: " + bytesReceived + SEPARATOR);
      dataLine.append("U: " + bytesSent + SEPARATOR);
      dataLine.append(carrier + SEPARATOR);
      dataLine.append(subtype + SEPARATOR);
      dataLine.append(version + SEPARATOR);
      dataLine.append(cellInfo + SEPARATOR);
      dataLine.append(dBm + SEPARATOR);
      dataLine.append(interrupted + SEPARATOR);
      dataLine.append(tld + SEPARATOR);
      dataLine.append(timeToLoad);
      
      BufferedWriter bW;

      bW = new BufferedWriter(new FileWriter(dataFile, true));
      bW.write(dataLine.toString());
      bW.newLine();
      bW.flush();
      bW.close();
    } catch (IOException e) {
      e.printStackTrace();
      Log.e("AdkinBrowser", e.toString());
    }
  }

  /**
   * Elimina el archivo de datos
   * @param deviceID ID del dispositivo
   * @return True en caso que el archivo sea eliminado, false en caso contrario
   */
  public static boolean deleteFile(String deviceID) {
    String filename = deviceID + "-browser.txt";
    File root = new File(Environment.getExternalStorageDirectory(), C.folder);

    if (!root.exists()) {
      return false;
    }
    File dataFile = new File(root, filename);
    return dataFile.delete();
  }
  
  /**
   * Intenta subir el archivo de datos, si es que existe el archivo, hay conectividad WIFI, y el usuario lo permite (segn preferencias)
   * @param deviceID ID del dispositivo
   * @param context Contexto desde el que se llama el mtodo
   * @return Estado final de la accion (true = exito | false = error)
   */
  public static boolean tryUpload(String deviceID, Context context){
    String filename = deviceID + "-browser.txt";
    File root = new File(Environment.getExternalStorageDirectory(), C.folder);
    File file = new File(root, filename);
    
    if(!getNetworkType(context).equalsIgnoreCase("wifi")){
      Log.d("Upload", "Not connected to WIFI");
      return false;
    }
    
    if(file.exists()){
      Log.i("archivo 1","existe");
      long tamano = file.length() / 1024;
      
      if( tamano >= 3) {
        Log.i("archivo","subiendo");
        if(subir(file.getName(), context) == true){
          file.delete();
          Log.i("archivo","borrado");
          return true;
        } else {
          Log.e("Upload","Fallo entrega archivo");
        }
      }
      else Log.i("archivo 1","aun no alcanza tamao min");
    }
    return false;
  }
  
  
  /** 
   * Sube un archivo especifico a un servidor (Mediante un HTTP POST).
   * @param nombreArchivo Nombre del archivo que se desea subir.
   * @return Estado final de la accion. (true = exito | false = error).
   */
  public static boolean subir(String filename, Context context){
      HttpURLConnection connection = null;
      DataOutputStream outputStream = null;

      File root = new File(Environment.getExternalStorageDirectory(), C.folder);
    File file = new File(root, filename);
    
      String pathToOurFile = file.getAbsolutePath();
      Log.d("IO", pathToOurFile);
      //String urlServer = "http://www.niclabs.cl/adkintun_mobile_upload/archivo.php";
      //String urlServer = "http://172.30.65.15/adkintun_mobile_upload-gabriel/archivo.php";
      String urlServer = C.server;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary =  "*****";
      String pathEncryptedFile;

      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1*1024*1024;
      
      try {
      
      RSAEncrypter rsa = new RSAEncrypter(context);
      AESEncrypter aes = new AESEncrypter(null);
      
      String salt = aes.getSalt();
      String password=aes.getPassword();
      String iv = aes.getIV();
      boolean worstcase= aes.isWorstcase();
      
      if (worstcase){
        pathEncryptedFile = pathToOurFile.concat(".hybrid_AESwc_RSA");
      } else {
        pathEncryptedFile = pathToOurFile.concat(".hybrid_AES_RSA");
      }
      /* "worst case" does not support PBKDF2WithHmacSHA1 algorithm, 
       * that's why the file has a different name
       */
      
      String symmetric_key_params = password + "\n" + salt  + "\n" + iv + "\n";
      
      byte[] encrypted_symmetric_key = rsa.stringEncrypter(symmetric_key_params);
      
      BufferedOutputStream bw = null;
      bw = new BufferedOutputStream(new FileOutputStream(pathEncryptedFile, false), 8192);
      bw.write(encrypted_symmetric_key);
      bw.flush();
      bw.close();
        
    aes.fileEncrypter(pathToOurFile, pathEncryptedFile, true);
    
      } catch (IOException e) {
      Log.e("error","error encrypting file " + e);
      return false;
    }

      try
      {
      File encryptedFile = new File(pathEncryptedFile);
      
      FileInputStream fileInputStream = new FileInputStream(encryptedFile);
      
      URL url = new URL(urlServer);
      connection = (HttpURLConnection) url.openConnection();
            
      // Allow Inputs & Outputs
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setUseCaches(false);

      // Enable POST method
      connection.setRequestMethod("POST");
      
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
      
      outputStream = new DataOutputStream( connection.getOutputStream() );
      outputStream.writeBytes(twoHyphens + boundary + lineEnd);
      outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathEncryptedFile +"\"" + lineEnd);      
      outputStream.writeBytes(lineEnd);
      
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];
      
      // Read file
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0)
      {
      outputStream.write(buffer, 0, bufferSize);
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }
      
      outputStream.writeBytes(lineEnd);
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      // Responses from the server (code and message)
      int serverResponseCode = connection.getResponseCode();
      String serverResponseMessage = connection.getResponseMessage();
      Log.d("CodRespuesta",serverResponseCode+"");
      Log.d("Respuesta",serverResponseMessage);
      
      if(serverResponseCode!=200) {
        fileInputStream.close();
          outputStream.flush();
          outputStream.close();
          return false;
        
      }
      
      fileInputStream.close();
      outputStream.flush();
      outputStream.close();
      
      encryptedFile.delete();
      
      return true;
      }
      catch (Exception ex)
      {
        Log.e("error",ex.getMessage());
        return false;
      //Exception handling
      }
    }
  
  /** 
  * Obtiene el tipo de red al que se esta conectado
    * @param c Contexto en el cual se ejecuta el metodo.
    * @return Tipo de red al que se esta conectado ( error en caso de no estar conectado).
    */
  public static String getNetworkType (Context c) {
    try{
      ConnectivityManager connectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
      return ni.getTypeName();

    } catch (Exception e) {
      System.out.println(e);
      Log.e("Conexion","No esta conectado");
      return "error";
    }
        
  
  }
}




Java Source Code List

cl.niclabs.adkintunmobile.browser.C.java
cl.niclabs.adkintunmobile.browser.Client.java
cl.niclabs.adkintunmobile.browser.CustomWebView.java
cl.niclabs.adkintunmobile.browser.DropDownAnim.java
cl.niclabs.adkintunmobile.browser.FileHandler.java
cl.niclabs.adkintunmobile.browser.MainActivity.java
cl.niclabs.adkintunmobile.browser.PreferencesActivity.java
cl.niclabs.adkintunmobile.browser.Register.java
cl.niclabs.adkintunmobile.browser.UrlUtils.java
cl.niclabs.adkintunmobile.crypto.AESEncrypter.java
cl.niclabs.adkintunmobile.crypto.Encrypter.java
cl.niclabs.adkintunmobile.crypto.RSAEncrypter.java