Android Open Source - Android-Universal-Notifier Network Operations






From Project

Back to project page Android-Universal-Notifier.

License

The source code is released under:

Apache License

If you think the Android project Android-Universal-Notifier 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

package com.mairos.universalnotifier.network;
/*from  w w w.j  a va  2s .  c o  m*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.mairos.universalnotifier.model.Const;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

public class NetworkOperations {
  
  public static class ResponseResult {
    public File m_resultFile;
    public String m_resultMessage;
    public ResponseResult(File f_resultFile, String f_resultMessage){
      m_resultFile = f_resultFile;
      m_resultMessage = f_resultMessage;
    }
  }
  
  public final static String SUCCESS = "success";
  private final static String TMP_FOLDER = "/download/";
  
  public static String preparXMLAnswerToJS(int f_code, String f_body){
    return "<responce>"
          + "<code>" + f_code + "</code>"
          + "<body><![CDATA[" + f_body + "]]></body>"
          + "</responce>";  
  }
  
  @SuppressLint("SimpleDateFormat")
  public static String getFtpFilesInfo(String f_URL, String f_login, String f_password, String f_folderName) {
    
    FTPClient client = new FTPClient();
    String result = "";
    try {
      client.connect(f_URL);
      if(client.isConnected())
        {
        if (client.login(f_login, f_password)){
          client.enterLocalPassiveMode();
          client.setAutodetectUTF8(true);
          
          if (client.changeWorkingDirectory(f_folderName)){
          
            // lists files and directories in the current working directory
            FTPFile[] files = client.listFiles();
             
            // iterates over the files and prints details for each
            SimpleDateFormat dateFormater = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
             
            String details = "";
            for (FTPFile file1 : files) {
              if (!file1.isDirectory()) {
                details = file1.getName();
                details += "&" + dateFormater.format(file1.getTimestamp().getTime());
                if (result != "") result += "||";
                result += details;
                }                
                Log.d(Const.LOG_TAG, details);
            }
          } else {
            return preparXMLAnswerToJS(4, "directory " + f_folderName + " not acceptable");
          }
        } else {
          return preparXMLAnswerToJS(3, "Can't connect to " + f_URL + " with " + f_login + " and " + f_password);
        }
        } else {
          return preparXMLAnswerToJS(2, "Can't connect to " + f_URL);
        }
    } catch (IOException e) {
      e.printStackTrace();
      return preparXMLAnswerToJS(1, "Connection to " + f_URL + " failed");
    }
    return preparXMLAnswerToJS(0, result);
  }
  public static File getFileFromFTP(String f_URL, String f_login, String f_password, String f_fileName){
    
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;
    
    String fileName = f_fileName.split("/")[f_fileName.split("/").length-1];
    
    File file = new File(Environment.getExternalStorageDirectory().getPath()+TMP_FOLDER+fileName);
    
    try {
      client.connect(f_URL);
      if (client.isConnected()){
        if (client.login(f_login, f_password)){
          client.enterLocalPassiveMode();
          client.setAutodetectUTF8(true);
          client.setFileType(FTPClient.BINARY_FILE_TYPE);
          fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+TMP_FOLDER+fileName);
          client.retrieveFile(f_fileName, fos);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    
    try {
      if (fos != null) {
        fos.flush();
          fos.close();
        }
      client.logout();
        client.disconnect();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    
    return file;
  }
  
  public static String loadAuthorizedHTTPPictureAndSave(String f_URL, String f_login, String f_pwd, String f_saveFileName) {
    ResponseResult result = getFileFromHTTP(f_URL, f_login, f_pwd, f_saveFileName, false);
    if (result.m_resultFile == null || !result.m_resultMessage.equals(SUCCESS)){
      return preparXMLAnswerToJS(1, "Error " + result.m_resultMessage);
    } else {
      return preparXMLAnswerToJS(0, f_URL + " successfully saved to " + f_saveFileName);
    }
  }
  
  public static ResponseResult getFileFromHTTP(String f_URL, String f_login, String f_pwd, String f_fileName, boolean f_saveInTmpFolder){
     String name = "";
     if (f_fileName != "")
       name = f_fileName;
     else
       name = f_URL.split("/")[f_URL.split("/").length-1];
       
     File file = null;
     if (f_saveInTmpFolder){
       file = new File(Environment.getExternalStorageDirectory().getPath()+TMP_FOLDER+name);
     } else {
       file = new File(f_fileName);
     }
     
       InputStream inputStream = null;
       FileOutputStream fileOutput = null;
       HttpURLConnection urlConnection = null;
       
    try {
          //set the download URL, a url that points to a file on the internet
          //this is the file to be downloaded
          URL url = new URL(f_URL);

          //create the new connection
          urlConnection = (HttpURLConnection) url.openConnection();

          //set up some things on the connection
          urlConnection.setRequestMethod("GET");
          
          if (f_login != "" || f_pwd != ""){
            String authData = "Basic " + Base64.encodeToString((f_login+":"+f_pwd).getBytes(), Base64.NO_WRAP);
            urlConnection.setRequestProperty ("Authorization", authData);
          }

          //and connect!
          urlConnection.connect();       
          
          //this will be used to write the downloaded data into the file we created
          fileOutput = new FileOutputStream(file);

          //this will be used in reading the data from the internet
          inputStream = urlConnection.getInputStream();

          int MAX_BUFFER_SIZE = 1024;
          long length = urlConnection.getContentLength();
          int bufferSize = (((int)length) > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length;
          //create a buffer...
          byte[] buffer = new byte[bufferSize];
          int bufferLength = 0; //used to store a temporary size of the buffer
          
          //now, read through the input buffer and write the contents to the file
          while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                  //add the data in the buffer to the file in the file output stream (the file on the sd card
                  fileOutput.write(buffer, 0, bufferLength);
          }
          
          //close the output stream when done
          if (fileOutput != null) fileOutput.close();
          urlConnection.disconnect();
    //catch some possible errors...
    } catch (MalformedURLException e) {
       Log.d(Const.LOG_TAG, "getFileFromHTTP MalformedURLException " + e.getMessage());
       e.printStackTrace();
       return new ResponseResult(file, e.getMessage());         
    } catch (IOException e) {
       Log.d(Const.LOG_TAG, "getFileFromHTTP IOException " + e.getMessage());
         e.printStackTrace();
         return new ResponseResult(null, e.getMessage());
    } finally {
          urlConnection.disconnect();
    }
    return new ResponseResult(file, SUCCESS);
  }

  public static String httpRequest(String f_URL){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(f_URL);
    
    //String authData = "Basic " + Base64.encodeToString(("admin:65536").getBytes(), Base64.NO_WRAP);
    //httppost.setHeader("Authorization", authData); 
    
    try {
      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);
      
      HttpEntity entity = response.getEntity();
      InputStream inputStream = entity.getContent();
      
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        return preparXMLAnswerToJS(0, sb.toString());
    } catch (ClientProtocolException e) {
      return preparXMLAnswerToJS(1, "ClientProtocolException");
    } catch (IOException e) {
      return preparXMLAnswerToJS(1, "ServerNoAcceptable");
    }
  }
  public static String saveStringToFile(String f_data, String f_path, Context f_context) {
    try {      
      FileWriter out = new FileWriter(new File(f_path));
            out.write(f_data);
            out.close();
      }
      catch (IOException e) {
          Log.e("Exception", "File write failed: " + e.toString());
          return preparXMLAnswerToJS(1, e.getMessage());
      }
    return preparXMLAnswerToJS(0, "saved successfully");
  }
  @SuppressWarnings("resource")
  public static String loadStringFromFile(String f_path, Context m_context) {
    StringBuilder stringBuilder = new StringBuilder();
        String line;
        BufferedReader in = null;
    
      try {
        in = new BufferedReader(new FileReader(new File(f_path)));
            while ((line = in.readLine()) != null) stringBuilder.append(line);
      }
      catch (FileNotFoundException e) {
          Log.e("login activity", "File not found: " + e.toString());
          return preparXMLAnswerToJS(1, e.getMessage());
      } catch (IOException e) {
          Log.e("login activity", "Can not read file: " + e.toString());
          return preparXMLAnswerToJS(1, e.getMessage());
      }

      return preparXMLAnswerToJS(0, stringBuilder.toString());
  }
}




Java Source Code List

com.mairos.universalnotifier.UI.LogFragmentTab.java
com.mairos.universalnotifier.UI.MainActivity.java
com.mairos.universalnotifier.UI.SettingsActivity.java
com.mairos.universalnotifier.UI.TabListener.java
com.mairos.universalnotifier.UI.TaskInfoActivity.java
com.mairos.universalnotifier.UI.TasksFragmentTab.java
com.mairos.universalnotifier.model.AlarmManagerBroadcastReceiver.java
com.mairos.universalnotifier.model.AttachmentData.java
com.mairos.universalnotifier.model.Const.java
com.mairos.universalnotifier.model.JSInterpreter.java
com.mairos.universalnotifier.model.LauncherBroadcastReceiver.java
com.mairos.universalnotifier.model.Logger.java
com.mairos.universalnotifier.model.NotificationService.java
com.mairos.universalnotifier.model.NotificationTask.java
com.mairos.universalnotifier.model.TasksQueue.java
com.mairos.universalnotifier.model.TasksXMLLoader.java
com.mairos.universalnotifier.network.GMailSender.java
com.mairos.universalnotifier.network.JSSEProvider.java
com.mairos.universalnotifier.network.NetworkOperations.java
com.mairos.universalnotifier.network.SMSSender.java