Skip to content

Instantly share code, notes, and snippets.

@basharam
Created May 15, 2020 12:41
Show Gist options
  • Save basharam/a8116835ada8bd50214af3393ac0ef5b to your computer and use it in GitHub Desktop.
Save basharam/a8116835ada8bd50214af3393ac0ef5b to your computer and use it in GitHub Desktop.
Send all files and subfolders over socker as ZIP file over Server on lookback adapter Android
:::Client :::
mZipFileName ="bla.zip";
main(){
DownloadThread mFileDNThread = new DownloadThread (mZipFileName,"welcome message");
mFileDNThread.start();
}
class DownloadThread extends Thread {
String mFilename;
String mIP;
DownloadThread(String afilename,String aIP){
this.mFilename= afilename;
this.mIP=aIP;
mStopThread=false;
}
public void abortThread(){
mStopThread=true;
}
@Override
public void run() {
// DownloadZippedfilewithInfo(mFilename,mIP);
DownloadAllFileswithInfo(mFilename,mIP);
return;
}
}
private void DownloadZippedfilewithInfo(String afilename, String aIP){
Socket socket = null;
InputStream in = null;
FileOutputStream out = null;
String filename=null;
String infomsg="";
int totalbytes = 0;
try {
File myExternalFile = new File(getExternalFilesDir(null), mZipFileName);
if (myExternalFile.exists())
myExternalFile.delete();
if (!myExternalFile.exists()) {
if (myExternalFile.createNewFile()) {
Log.e(TAG, "file created: ");
}
}
socket = new Socket(InetAddress.getByName(null), Globaldata.PORT);
Log.w(TAG, "Connecting...");
sendMsg("Connecting...");
DataInputStream dIn = new DataInputStream(socket.getInputStream());
boolean done = false;
while (!done && !mStopThread) {
if(dIn.available()>0) {
byte messageType = dIn.readByte();
switch (messageType) {
case 1: // Type A
infomsg= dIn.readUTF();
Log.e(TAG, messageType+": MessageType: "+ infomsg);
sendMsg(infomsg);
break;
case 2: // Type B
infomsg= dIn.readUTF();
Log.e(TAG, messageType + ": MessageType: "+infomsg);
sendMsg(infomsg);
break;
case 3: // Type C
Log.e(TAG, "Message C: " + dIn.readUTF());
break;
case 4: // Type D
Log.e(TAG, "Default: " + messageType);
filename = dIn.readUTF();
sendMsg("downloading zipped file..."+filename);
done = true;
break;
default:
break;
}
}else {
Log.e(TAG, "Sleeping " );
Globaldata.sleepInsec(500);
}
}
if (filename!=null && filename.contains(".zip")) {
//Initialize the FileOutPutStream
out = new FileOutputStream(myExternalFile.getAbsolutePath());
totalbytes=0;
sendMsg("downloading file..."+filename);
// 1MB Buffer
byte[] mb = new byte[Globaldata.ONE_MB_BUFFER];// new byte[16 * 1024];//
// sendfile
for (int c = dIn.read(mb); c > -1; c = dIn.read(mb)) {
Log.w(TAG, "read and wrote: " + c + " Bytes");
out.write(mb, 0, c);
totalbytes += c;
}
}
if(out!=null)
out.close();
if(dIn!=null)
dIn.close();
if(socket!=null)
socket.close();
if(totalbytes!=0) {
Log.w(TAG, "Receiving file completed");
ZipManager.unzip(myExternalFile.getAbsolutePath(), myExternalFile.getParent());
Log.w(TAG, "unzip received file completed");
sendMsg("Done Download completed...");
}
if(mStopThread){
sendMsg("Download cancelled...");
}
}catch (IOException ioe){
ioe.printStackTrace();
sendMsg("Server: Not Reachable");
}
}
::::Server:::
private class HttpServerThread extends Thread {
@Override
public void run() {
Socket socket = null;
try {
mServerSocket = new ServerSocket(Globaldata.PORT, 0, InetAddress.getByName(null));
updateUI("Server: Up and Running");
while(true){
socket = mServerSocket.accept();
ResponseThread responseThread =
new ResponseThread(
socket,
"welcome message");
responseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
updateUI("Server: "+e.getMessage());
e.printStackTrace();
}
}
}
private void sendZippedFilesWithInfo(Socket socket, String h1){
FileInputStream in=null;
destZIPFile =new File(getExternalFilesDir(null), zipfileName);
srcFiles = getExternalFilesDir(Globaldata.BASE_PATH);
String zipfile =destZIPFile.getAbsolutePath();
mIsFilezipped=false;
ZipManager.mTotalfiles=0;
int files= ZipManager.getNumberofFiles(srcFiles.getParent());
mHandler.post(createArchive);
mFoldersize=0;
mNumofFiles=0;
mHandler.post(getallfilesandfolders);
int totalbytes=0;
try {
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
boolean done = false;
while (!done) {
// Send first message
Log.w(TAG, "Senging 1:"+ZipManager.getZipStatus());
dOut.writeByte(1);
dOut.writeUTF(ZipManager.getZipStatus());
dOut.flush(); // Send off the data
Globaldata.sleepInsec(250);
// Send the second message
Log.w(TAG, ""+" size:"+destZIPFile.length());
dOut.writeByte(2);
dOut.writeUTF("all files zipped :"+mIsFilezipped +
" Zip file size:"+destZIPFile.length() /*+" files:"+mNumofFiles*/);
dOut.flush(); // Send off the data
Globaldata.sleepInsec(250);
if(mIsFilezipped) {
Log.w(TAG, "closing loop");
done = true;
}
Globaldata.sleepInsec(1500);
}
in = new FileInputStream(zipfile);
// String[] pathasarray= afilename.split("/");
// Log.e(TAG,"filname name: "+pathasarray[pathasarray.length-1]);
// Send the messageType D
dOut.writeByte(4);
dOut.writeUTF(zipfileName);
dOut.flush();
Log.w(TAG, "sending file");
//1 MB
byte[] mb = new byte[Globaldata.ONE_MB_BUFFER];
for(int c = in.read(mb, 0, Globaldata.ONE_MB_BUFFER); c > 0;
c = in.read(mb, 0, Globaldata.ONE_MB_BUFFER)){
dOut.write(mb, 0, c);
totalbytes+=c;
}
if(dOut!=null) {
dOut.flush();
dOut.close();
}
if(in!=null) {
in.close();
}
if(socket!=null)
socket.close();
Log.w(TAG, "sending file completed");
msgLog += "Download Request for: " +zipfileName + ": "+totalbytes+" Bytes."+"\n";
updateReqestLog();
ServerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mInfomsg.setText(msgLog);
}
});
}catch (IOException ioe){
Log.e(TAG,"exception: "+ ioe.getMessage());
msgLog+="Exception: "+ioe.getMessage()+"\n";
}
}
::ZIP tool::
public class ZipManager {
private static final String TAG ="ZipManager" ;
private static int BUFFER_SIZE = 6 * 1024;
static int mTotalfiles = 0;
static int mFilesZipped=0;
public static void zip(String[] files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}
}
public static int getNumberofFiles(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();
mTotalfiles += files.length;
// Log.w("server logs"," dirpath:"+dirPath+": "+ mTotalfiles);
if (files != null){
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
mTotalfiles--;
getNumberofFiles(file.getAbsolutePath());
}
}
}
return mTotalfiles;
}
public static String getZipStatus(){
String filezipped = mFilesZipped+"/"+mTotalfiles;
return filezipped;
}
public static boolean unzip(String azipFile, String location) throws IOException {
File zipFile=new File(azipFile);
File destinationDir= new File(location);
ZipFile zip = null;
try {
destinationDir.mkdirs();
zip = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
while (zipFileEntries.hasMoreElements()) {
ZipEntry entry = zipFileEntries.nextElement();
String entryName = entry.getName();
File destFile = new File(destinationDir, entryName);
Log.w(TAG, "destFile :"+destFile );
File destinationParentDir = destFile.getParentFile();
if (destinationParentDir != null && !destinationParentDir.exists()) {
destinationParentDir.mkdirs();
}
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
byte data[] = new byte[BUFFER_SIZE];
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Log.w(TAG, "unzip done");
return true;
}
/*
*
* Zips a file at a location and places the resulting zip file at the toLocation
* Example: zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
*/
public static boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
mFilesZipped=0;
File sourceFile = new File(sourcePath);
File destination= new File(toLocation);
if(!destination.exists()){
destination.delete();
}
try {
destination.createNewFile();
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
mFilesZipped++;
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/*
*
* Zips a subfolder
*
*/
private static void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
final int BUFFER = 2048;
boolean folderexists = folder.exists();
Log.d(TAG, "folderExists:"+folderexists);
File[] fileList = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
Log.e("file","dir: "+dir+" filename: "+name);
if (name.toLowerCase().endsWith(".zip"))
return false;
return true;
}
});
Log.w(TAG,"fillist array:"+ Arrays.deepToString(fileList));
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
mFilesZipped++;
origin.close();
}
}
}
/*
* gets the last path component
*
* Example: getLastPathComponent("temp/dir1/fileToZip");
* Result: "fileToZip"
*/
public static String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment