Tuesday, July 24, 2012

How to Upload Zip File through SOAP in Android?



Below is class File which uploads the zip file...




import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class UploadWebservice extends Activity {
private static String SOAP_ACTION = "http://tempuri.org/";
private static String METHOD_NAME = "";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.100.114/Webservice/Service1.asmx";
static HashMap<String, String> propertiesMap;
private static boolean isUploadSuccessfull;
//private static final String SOAP_ACTION = "http://tempuri.org/ITransferService/UploadFile";
 //private static final String SOAP_ACTION = "\"http://tempuri.org/ITransferService/UploadFile\"";

private static int incrementBy=0;
static Handler handler;
static Dialog downloadProgressdialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

propertiesMap = new HashMap<String,String>();
METHOD_NAME = "";
METHOD_NAME = "UploadLog";
SOAP_ACTION = "http://tempuri.org/";
SOAP_ACTION = SOAP_ACTION+METHOD_NAME;
propertiesMap.put("emailid","shuklaxyz@yahoo.com");
propertiesMap.put("password","abc");
propertiesMap.put("FileName","abc.zip");
propertiesMap.put("FolderName","Shailesh");

Call();


handler = new Handler() {


public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
LayoutInflater factory = LayoutInflater.from(UploadWebservice.this);          
final View progressDialogView = factory.inflate(R.layout.progressbar, null);
TextView progressTV =  (TextView)progressDialogView.findViewById(R.id.progressbarpercentagetxt);
ProgressBar downloadProgressBar = (ProgressBar)progressDialogView.findViewById(R.id.progress_bar);


incrementBy =incrementBy+total/2;
downloadProgressBar.setMax(total);
downloadProgressBar.incrementProgressBy(incrementBy);
if(incrementBy<total)
progressTV.setText(Integer.toString((incrementBy*100)/total)+"% Completed");
else{
downloadProgressBar.setProgress(total);
progressTV.setText("100% Completed");
}
downloadProgressdialog.setContentView(progressDialogView);
downloadProgressdialog.show();

if(downloadProgressBar.getProgress() == downloadProgressBar.getMax()){
System.out.println("Completed upload");
downloadProgressdialog.dismiss();
incrementBy = 0;

if(isUploadSuccessfull){
AlertDialog.Builder adb=new AlertDialog.Builder(UploadWebservice.this);
adb.setTitle("guideVue");
adb.setMessage("Logs Uploaded Successfully.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

}

});

adb.show();
}else{
AlertDialog.Builder adb=new AlertDialog.Builder(UploadWebservice.this);
adb.setTitle("guideVue");
adb.setMessage("Problem occured while uploading,Please try again later.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

}

});

adb.show();
}
}

}
};

}




public static void Call() {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Iterator<String> ite = propertiesMap.keySet().iterator();
while (ite.hasNext()) {
String key = (String) ite.next();
String value = (String) propertiesMap.get(key);
request.addProperty(key, value);
System.out.println("Kye|Value:" + key + "|" + value);
}

String log_zipFile="sdcard/a/b/abc.zip";
final byte[] bytebuffer = convertToByteArray(new File(log_zipFile));
System.out.println("***ByteBuffer:" + bytebuffer.length);

Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", bytebuffer.length);
msg.setData(b);

request.addProperty("logsbuffer", bytebuffer/*
* Base64.encode(bytebuffer,
* Base64.DEFAULT)
*/);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

MarshalBase64 marshal = new MarshalBase64();
marshal.register(envelope);
System.out.println("Webservice URL UploadLog:" + URL + METHOD_NAME);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
SoapPrimitive result = null;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
result = (SoapPrimitive) envelope.getResponse();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


System.out.println("Webservice Result UploadLog:" + result.toString());
isUploadSuccessfull = Boolean.parseBoolean(result.toString());
if (log_zipFile.endsWith(".zip"))
new File(log_zipFile).delete();
}

private static byte[] convertToByteArray(final File file) {
   if (file.isDirectory())
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is a directory");
   if (file.length() > Integer.MAX_VALUE)
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is too big");

   Throwable pending = null;
   FileInputStream in = null;
   final byte buffer[] = new byte[(int) file.length()];
   try {
       in = new FileInputStream(file);
       in.read(buffer);
   } catch (Exception e) {
       pending = new RuntimeException("Exception occured on reading file "
                       + file.getAbsolutePath(), e);
   } finally {
       if (in != null) {
               try {
                       in.close();
               } catch (Exception e) {
                       if (pending == null) {
                               pending = new RuntimeException(
                                       "Exception occured on closing file"
                            + file.getAbsolutePath(), e);
                       }
               }
       }
       if (pending != null) {
               throw new RuntimeException(pending);
       }
   }
   return buffer;
}

}






Below is the progressbar.xml for Showing Progress Dialog.......


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="15px" >

    <TextView
        android:id="@+id/progressbartxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Please wait..." />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10px" />

    <TextView
        android:id="@+id/progressbarpercentagetxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="0% Completed" />

</LinearLayout>









No comments:

Post a Comment