Showing posts with label SOAP. Show all posts
Showing posts with label SOAP. Show all posts

Thursday, August 23, 2012

How to retrieve arrayList object through SOAP?

After retrieving data from the Server side through SOAP.....you can store it in the Vector collection and the store it in the Class Object property........!!!!!!!!

Declare the List variables for storing the array object


private  List<String>  downloadList= new ArrayList<String>();
private  List<String>  usenameAttr = new ArrayList<String>();
private  List<String>  imageList = new ArrayList<String>();
private  List<String>  purposeList = new ArrayList<String>();

then create the List of class type for storing the value

List<GVDownlaodObjectEntity>  downloadGVObjectList= new ArrayList<GVDownlaodObjectEntity>();

Where GVDownlaodObjectEntity is a class below.........


package com.ags.entity;

public class GVDownlaodObjectEntity {


private String info="";

private String gvThumbnail="";

private String gvTitle="";

private String gvUserName="";

public String getGvUserName() {
return gvUserName;
}

public void setGvUserName(String gvUserName) {
this.gvUserName = gvUserName;
}

public String getInfo() {
return info;
}

public void setInfo(String info) {
this.info = info;
}

public String getGvThumbnail() {
return gvThumbnail;
}

public void setGvThumbnail(String gvThumbnail) {
this.gvThumbnail = gvThumbnail;
}

public String getGvTitle() {
return gvTitle;
}

public void setGvTitle(String gvTitle) {
this.gvTitle = gvTitle;
}


}



then retrieves the response and see how to get the data and store it in property....




Vector result = (Vector)envelope.getResponse();
System.out.println("result:"+ result.get(0));

for(int i = 0; i < ((SoapObject) result.get(0)).getPropertyCount(); i++) {
String  gvdownloadObject =  ((SoapObject) result.get(0)).getProperty(i).toString();
int firstIndex =gvdownloadObject.indexOf("{");
String newListGVObject = gvdownloadObject.substring(firstIndex+1, gvdownloadObject.length()-1);
System.out.println("NewGVObject["+i+"]:"+gvdownloadObject);
StringTokenizer str= new StringTokenizer(newListGVObject,";");
GVDownlaodObjectEntity gVDownlaodObjectEntity = new GVDownlaodObjectEntity();
while (str.hasMoreTokens()) {
String token = str.nextToken().trim();
System.out.println("Token:"+token);
 
if(token.compareToIgnoreCase("") != 0){
String gvDownloadTokens=token.substring(0,token.indexOf('='));
System.out.println("ObjectTokens:"+gvDownloadTokens);
if(gvDownloadTokens.compareToIgnoreCase("UserName") == 0){
gVDownlaodObjectEntity.setGvUserName(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("GvInfo") == 0){
gVDownlaodObjectEntity.setInfo(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("GvThumb") == 0){
gVDownlaodObjectEntity.setGvThumbnail(token.substring(token.indexOf('=')+1,token.length()));
}else if(gvDownloadTokens.compareToIgnoreCase("Id") == 0)
gVDownlaodObjectEntity.setGvId(token.substring(token.indexOf('=')+1,token.length()));
else if(gvDownloadTokens.compareToIgnoreCase("GvTitle") == 0){
gVDownlaodObjectEntity.setGvTitle(token.substring(token.indexOf('=')+1,token.length()));

downloadList.add(gVDownlaodObjectEntity.getGvTitle());
purposeList.add(gVDownlaodObjectEntity.getInfo());
usenameAttr.add(gVDownlaodObjectEntity.getGvUserName());
imageList.add(gVDownlaodObjectEntity.getGvThumbnail());

}
}


}
if(gVDownlaodObjectEntity != null)
downloadGVObjectList.add(gVDownlaodObjectEntity);
System.out.println("downloadGVObjectList size:"+downloadGVObjectList.size()+"|"+downloadGVObjectList.get(i).getGvThumbnail());
}

totalRecords=Integer.parseInt(((SoapObject) result.get(1)).toString());
System.out.println("total count from server:"+totalRecords);







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>









Monday, June 4, 2012

Android emulator: How to monitor network traffic?


There are two ways to capture network traffic directly from an Android emulator:
  1. Copy and run an ARM-compatible tcpdump binary on the emulator, writing output to the SD card, perhaps (e.g. tcpdump -s0 -w /sdcard/emulator.cap).
  2. Run emulator -tcpdump emulator.cap -avd my_avd to write all the emulator's traffic to a local file on your PC
In both cases you can then analyse the pcap file with tcpdump or Wireshark as normal.

try wireshark http://www.wireshark.org/

Capture network trace in Android devices ?


After finding a bug, the next step for a tester is to find whose fault is it ? 
Normally a software interacts a lot with servers. It is then quite useful to capture the network exchanges between the software and the servers to find what is really happening behind the user interface. For Android devices, we can use Android Debug Bridge (ADB), tcpdump-arm and wireshark to analyse network packages. First, you need to have Wireshark and ADB installed in your computer (here’s a bit oftutorial). Then, I’ll briefly explain how to use tcpdump-arm in your Android devices to capture a network trace during use case scenario.
1.    Download tcpdump-arm from here
2.    Open command-promt where your ADB tools located. Put your tcpdump-arminto /data/local in your Android device through this command :

adb remount
adb push tcpdump-arm /data/local
3.    Go inside Android devices through this command :

adb shell
cd data/local
4.    Give tcpdump-arm execute permission.

chmod 777 tcpdump-arm
5.    We need to define in which interface we want to listen to the packages. If you run the command below, you’ll see the list of interfaces registered on your device. Normally we find three interfaces: svnet0pdp0, and l0.

./tcpdump-arm -D
6.    Since I want to capture packets coming from data network, I choose to listen to interface: pdp0. (Still remember the famous Packet Data Protocol Context learnt at school  ). I specify also the output file in which I’d like it to be read through Wireshark later on.

./tcpdump-arm -i pdp0 -w capture.pcap
7.    FYI, the option of pdp0 is available when you use the firmware Gingerbread for Samsung Galaxy 2. When you use Ice Scream Sandwich, there’ll be only two options offered: svnet0 and l0. You can either listening to svnet0, but sometimes I also try with option -s 0 to make it capture the full packets and later on I filter what I want in wireshark.

./tcpdump-arm -s 0 -w capture.pcap
8.    After finish the test, run Ctrl+C to stop the capture. Move the output filecapture.pcap from the device into your computer and open it in Wireshark. Here you can do whatever filter you want to find your exchange package.

adb pull data/local/capture.pcap
These tricks have helped me a lot to prevent myself from blaming the developpers for some faults since it’s proved that the bug comes from another source  . Have fun!

Monday, January 30, 2012

How to send request through SOAP?

Just put the Soap.jar file in the lib folder of your application..........

public static String getResponse(String namespace, String url, String soapAction, String methodName, String requestString,Context context) {
String response = null;

SoapObject request = new SoapObject(namespace, methodName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
  //you can add multiple parameters with the help of addProperty
request.addProperty("xmlString", requestString);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;

try {
Log.e("Sending Request", requestString);
androidHttpTransport.call(soapAction, envelope);
Object soapResponse = envelope.getResponse();


if(soapResponse!=null){
response = soapResponse.toString();}
else{
response="";}

Log.e("Getting Response", response);

} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}

return response;
}