KSOAP Complex response parsing - parsing

I am currently using KSOAP2 for my project which is linked to a SOAP WebService. So far I have managed to get a result but now i had like to parse that result into a POJO. I have read that with using addMapping(namespace,node,class)
I could get my result into that Object but I don't know where is the problem in my code.
So my question would be: How to parse KSOAP response into my custom Object?
the wsdl : http://www.webservicex.net/geoipservice.asmx?wsdl
My XML Response
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetGeoIPResponse xmlns="http://www.webservicex.net/">
<GetGeoIPResult>
<ReturnCode>1</ReturnCode>
<IP>127.0.0.1</IP>
<ReturnCodeDetails>Success</ReturnCodeDetails>
<CountryName>Reserved</CountryName>
<CountryCode>ZZZ</CountryCode>
</GetGeoIPResult>
</GetGeoIPResponse>
</soap:Body>
</soap:Envelope>
MainActivity.java
private static final String SOAP_ACTION = "http://www.webservicex.net/GetGeoIP";
private static final String METHOD_NAME = "GetGeoIP";
private static final String NAMESPACE = "http://www.webservicex.net/";
private static final String URL = "http://www.webservicex.net/geoipservice.asmx?wsdl";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
addProperty("IPAddress","127.0.0.1");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet= true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.addMapping(NAMESPACE,"getGeoIPResponse", new GetGeoIPResponse().getClass());
soapEnvelope.addMapping(NAMESPACE,"getGeoIPResult", new GetGeoIPResult().getClass());
soapEnvelope.implicitTypes = true;
HttpTransportSE transport = new HttpTransportSE(URL);
transport.debug = true;
try {
transport.call(SOAP_ACTION, soapEnvelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
SoapObject resultString = (SoapObject) soapEnvelope.bodyIn;
Log.i(TAG, "Result: " + resultString);
} catch (Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
GetGeoResponse.java
public class GetGeoIPResponse implements KvmSerializable{
GetGeoIPResult getGeoIPResult = new GetGeoIPResult();
#Override
public Object getProperty(int index) {
if( index == 0 ){
return this.getGeoIPResult;
}
return null;
}
#Override
public int getPropertyCount() {
return 1;
}
#Override
public void setProperty(int index, Object value) {
if( index == 0){
this.getGeoIPResult =(GetGeoIPResult) value;
}
}
#Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
if(index == 0){
info.name = "GetGeoIPResult";
info.type = GetGeoIPResult.class;
}
}
}
GetGeoIPResult.java
public class GetGeoIPResult implements KvmSerializable {
private Integer returnCode;
private String IP;
private String returnCodeDetails;
private String countryName;
private String countryCode;
#Override
public Object getProperty(int index) {
switch (index){
case 0: return returnCode;
case 1: return IP;
case 2: return returnCodeDetails;
case 3: return countryName;
case 4: return countryCode;
default: return null;
}
}
#Override
public int getPropertyCount() {
return 5;
}
#Override
public void setProperty(int index, Object value) {
switch (index){
case 0:
returnCode = Integer.parseInt(value.toString());
break;
case 1:
IP = value.toString();
break;
case 2:
returnCodeDetails = value.toString();
break;
case 3:
countryName = value.toString();
break;
case 4:
countryCode = value.toString();
break;
default:
break;
}
}
#Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
switch (index){
case 0:
info.name = "ReturnCode";
info.type = PropertyInfo.INTEGER_CLASS;
break;
case 1:
info.name = "IP";
info.type = PropertyInfo.STRING_CLASS;
break;
case 2:
info.name = "ReturnCodeDetails";
info.type = PropertyInfo.STRING_CLASS;
break;
case 3:
info.name = "CountryName";
info.type = PropertyInfo.STRING_CLASS;
break;
case 4:
info.name = "CountryCode";
info.type = PropertyInfo.STRING_CLASS;
break;
default:
break;
}
}
}

I actually found out myself here are the files:
Request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("IPAddress","127.0.0.1");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet= true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.addMapping(NAMESPACE,"GetGeoIPResponse", GetGeoIPResponse.class);
soapEnvelope.addMapping(NAMESPACE,"GetGeoIPResult", GetGeoIPResult.class);
soapEnvelope.implicitTypes = true;
HttpTransportSE transport = new HttpTransportSE(URL);
transport.debug = true;
transport.call(SOAP_ACTION, soapEnvelope);
GetGeoIPResponse resultString = (GetGeoIPResponse) soapEnvelope.bodyIn;
GetGeoIPResult.java
public class GetGeoIPResult implements KvmSerializable {
private Integer returnCode;
private String IP;
private String returnCodeDetails;
private String countryName;
private String countryCode;
#Override
public Object getProperty(int index) {
switch (index){
case 0: return returnCode;
case 1: return IP;
case 2: return returnCodeDetails;
case 3: return countryName;
case 4: return countryCode;
default: return null;
}
}
#Override
public int getPropertyCount() {
return 5;
}
#Override
public void setProperty(int index, Object value) {
switch (index){
case 0:
returnCode = Integer.parseInt(value.toString());
break;
case 1:
IP = value.toString();
break;
case 2:
returnCodeDetails = value.toString();
break;
case 3:
countryName = value.toString();
break;
case 4:
countryCode = value.toString();
break;
default:
break;
}
}
#Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
switch (index){
case 0:
info.name = "ReturnCode";
info.type = PropertyInfo.INTEGER_CLASS;
break;
case 1:
info.name = "IP";
info.type = PropertyInfo.STRING_CLASS;
break;
case 2:
info.name = "ReturnCodeDetails";
info.type = PropertyInfo.STRING_CLASS;
break;
case 3:
info.name = "CountryName";
info.type = PropertyInfo.STRING_CLASS;
break;
case 4:
info.name = "CountryCode";
info.type = PropertyInfo.STRING_CLASS;
break;
default:
break;
}
}
}
GetGeoIPResponse.java
public class GetGeoIPResponse implements KvmSerializable {
private GetGeoIPResult getGeoIPResult;
#Override
public Object getProperty(int index) {
switch (index){
case 0:
return getGeoIPResult;
default: return null;
}
}
#Override
public int getPropertyCount() {
return 1;
}
#Override
public void setProperty(int index, Object value) {
switch (index){
case 0:
getGeoIPResult = (GetGeoIPResult) value;
break;
}
}
#Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
switch (index){
case 0:
info.name = "GetGeoIPResult";
info.type = GetGeoIPResult.class;
break;
}
}
}

Related

Audit change log not recording not Primary key on Create

I created an Audit Change log, from an example found here https://codewithmukesh.com/blog/audit-trail-implementation-in-aspnet-core/
public class ApplicationDbContext : IdentityDbContext
{
private IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
public override int SaveChanges()
{
AddAuditLog();
return base.SaveChanges();
}
private void AddAuditLog()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
ChangeTracker.DetectChanges();
var auditEntries = new List<AuditEntry>();
foreach (var entry in ChangeTracker.Entries())
{
if (entry.Entity is AuditLog || entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
continue;
var auditEntry = new AuditEntry(entry);
auditEntry.TableName = entry.Entity.GetType().Name;
auditEntry.UserId = userId;
auditEntries.Add(auditEntry);
foreach (var property in entry.Properties)
{
string propertyName = property.Metadata.Name;
if (property.Metadata.IsPrimaryKey())
{
auditEntry.KeyValues[propertyName] = property.CurrentValue;
continue;
}
switch (entry.State)
{
case EntityState.Added:
auditEntry.AuditType = AuditType.Create;
auditEntry.NewValues[propertyName] = property.CurrentValue;
break;
case EntityState.Deleted:
auditEntry.AuditType = AuditType.Delete;
auditEntry.OldValues[propertyName] = property.OriginalValue;
break;
case EntityState.Modified:
if (property.IsModified)
{
auditEntry.ChangedColumns.Add(propertyName);
auditEntry.AuditType = AuditType.Update;
auditEntry.OldValues[propertyName] = property.OriginalValue;
auditEntry.NewValues[propertyName] = property.CurrentValue;
}
break;
}
}
}
foreach (var auditEntry in auditEntries)
{
AuditLogs.Add(auditEntry.ToAudit());
}
}
All works as expected, except the Primary Key (Id) is not logged on CREATE.
All the primary keys of new records are recorded in the log as {"Id":-2147482647}, for some reason.
Is it possible to log the newly created Key?
Or is the problem that the Key is only created once the SaveChanges is completed and therefore could not be logged.
In the example referenced above the author seems to have it working
Your code doesn't work with database generated values. You need to read their values after saving entities to the database.
Original post (with more details): Entity Framework Core: History / Audit table
// https://www.meziantou.net/entity-framework-core-history-audit-table.htm
public class SampleContext : DbContext
{
public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
var auditEntries = OnBeforeSaveChanges();
var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
await OnAfterSaveChanges(auditEntries);
return result;
}
private List<AuditEntry> OnBeforeSaveChanges()
{
ChangeTracker.DetectChanges();
var auditEntries = new List<AuditEntry>();
foreach (var entry in ChangeTracker.Entries())
{
if (entry.Entity is Audit || entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
continue;
var auditEntry = new AuditEntry(entry);
auditEntry.TableName = entry.Metadata.GetTableName();
auditEntries.Add(auditEntry);
foreach (var property in entry.Properties)
{
if (property.IsTemporary)
{
// value will be generated by the database, get the value after saving
auditEntry.TemporaryProperties.Add(property);
continue;
}
string propertyName = property.Metadata.Name;
if (property.Metadata.IsPrimaryKey())
{
auditEntry.KeyValues[propertyName] = property.CurrentValue;
continue;
}
switch (entry.State)
{
case EntityState.Added:
auditEntry.NewValues[propertyName] = property.CurrentValue;
break;
case EntityState.Deleted:
auditEntry.OldValues[propertyName] = property.OriginalValue;
break;
case EntityState.Modified:
if (property.IsModified)
{
auditEntry.OldValues[propertyName] = property.OriginalValue;
auditEntry.NewValues[propertyName] = property.CurrentValue;
}
break;
}
}
}
foreach (var auditEntry in auditEntries.Where(_ => !_.HasTemporaryProperties))
{
Audits.Add(auditEntry.ToAudit());
}
return auditEntries.Where(_ => _.HasTemporaryProperties).ToList();
}
private Task OnAfterSaveChanges(List<AuditEntry> auditEntries)
{
if (auditEntries == null || auditEntries.Count == 0)
return Task.CompletedTask;
foreach (var auditEntry in auditEntries)
{
foreach (var prop in auditEntry.TemporaryProperties)
{
if (prop.Metadata.IsPrimaryKey())
{
auditEntry.KeyValues[prop.Metadata.Name] = prop.CurrentValue;
}
else
{
auditEntry.NewValues[prop.Metadata.Name] = prop.CurrentValue;
}
}
Audits.Add(auditEntry.ToAudit());
}
return SaveChangesAsync();
}
}

LinkList for beginner

public class Node {
int item;
Node next;
public Node() {
item = 0;
this.next = null;
}
public Node(int c) {
item = c;
next = null;
}
public Node(int c, Node next) {
item = c;
this.next = next;
}
}
public class List {
Node head;
Node tail;
int size;
public boolean isEmpty(){
return head == null;
}
public int size(){
return size;
}
public void addF(int i){
head = new Node(i, head);
size++;
}
public void addE(int i){
if(head == null){
Node s = new Node(i);
tail = head;
}else{
Node s = head;
while(s.next != null){
s = s.next;
}
s.next = new Node(i);
size++;
}
}
public static void main(String[] args){
List l = new List();
l.addF(55);
l.addF(56);
l.addF(57);
l.addE(54);
l.addE(53);
System.out.println(l.toString());
}
public String toString() {
String result = "[ ";
Node current = head;
while (current != null) {
result = result + current.item + " ";
current = current.next;
}
return result + "]";
}
}
Can anyone explain how the method addE() about else statement in detail for me please? I understand if statement but not else. I'm trying to understand it better. Thank you!!!
I think the code should be as follows:-
public void addE(int i){
if(head == null){
Node s = new Node(i);
head=s; //If the link list is empty then the first element(node) is the head
}else{
while(s.next != null){ //Traverse the entire linked list until you raech the tail
s = s.next;
}
s.next = new Node(i);//add the new node
size++;
}
}

Images are loading on simulater but not on Blackberry device

I am using following code to download images from server
public Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url+ ConnectionType.getConnectionType());
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
and ConnetionType class is as follows
public class ConnectionType {
public static String getConnectionType()
{
String connectionString = null;
if (DeviceInfo.isSimulator())
{
connectionString = "";
return connectionString;
}
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
return connectionString;
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null)
{
connectionString = ";deviceside=true";
return connectionString;
}
else
{
connectionString=carrierUid;
return connectionString;
}
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
return connectionString;
}
else
{
connectionString = ";deviceside=true";
return connectionString;
]
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The UID used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if (records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
//otherwise, use the UID to construct a valid carrier BIB-S
String carrierUid= records[currentRecord].getUid();
String extension = ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
return extension;
}
}
}
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("wptcp"))
{
String carrierUid= records[currentRecord].getUid();
String extension = ";ConnectionUID="+carrierUid;
return extension;
}
}
return null;
}
}
Images are displaying fine on simulater but when I run this on my device No image displayed .Please suggest where I am missing.
Thanks!!!

Get suffix string for BlackBerry connection on 4.6.1?

I'm trying to develop an application which uses HttpRequest for requesting a web page. The problem is that I still can't find the right way to get the suffix in the connection string for OS 4.6.1.
Thanks.
The links I believe I used to create my connection strings, pre OS 5.0, were these two:
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879
http://docs.blackberry.com/en/developers/deliverables/34480/Network_transport_options_1293321_11.jsp
BlackBerry of course supports several different transports (Wifi, WAP, BIS, etc.). You probably want to decide which transport you would like to use, and create your connection string depending on which transports are available at any one time, and on your priority.
Here's some more sample code to download from blackberry.com that helps build connection string suffixes. See the attachment links near the bottom for the actual downloads.
Also, if you're in a time crunch, and don't have time to read the resources I listed in my other answer, and just want some quick code, I remember there was an implementation in BlackBerry's original Facebook SDK that looked close to what I wrote myself (sorry, I can't post that code I wrote, because it's my client's). But, the Facebook SDK implementation appears to be free to publish. I can't find a link to it anymore, but I'll paste it below for your enjoyment:
/**
* Copyright (c) E.Y. Baskoro, Research In Motion Limited.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This License shall be included in all copies or substantial
* portions of the Software.
*
* The name(s) of the above copyright holders shall not be used
* in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*
*/
package com.blackberry.util.network;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.blackberry.util.log.Logger;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Branding;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.WLANInfo;
public class HttpConnectionFactory {
public static final int TRANSPORT_WIFI = 1;
public static final int TRANSPORT_BES = 2;
public static final int TRANSPORT_BIS = 4;
public static final int TRANSPORT_DIRECT_TCP = 8;
public static final int TRANSPORT_WAP2 = 16;
public static final int TRANSPORT_SIM = 32;
public static final int TRANSPORTS_ANY = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int TRANSPORTS_AVOID_CARRIER = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_SIM;
public static final int TRANSPORTS_CARRIER_ONLY = TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int DEFAULT_TRANSPORT_ORDER[] = { TRANSPORT_SIM, TRANSPORT_WIFI, TRANSPORT_BIS, TRANSPORT_BES, TRANSPORT_WAP2, TRANSPORT_DIRECT_TCP };
private static final int TRANSPORT_COUNT = DEFAULT_TRANSPORT_ORDER.length;
// private static ServiceRecord srMDS[], srBIS[], srWAP2[], srWiFi[];
private static ServiceRecord srWAP2[];
private static boolean serviceRecordsLoaded = false;
private int transports[];
private int lastTransport = -1;
protected Logger log = Logger.getLogger(getClass());
public HttpConnectionFactory() {
this(0);
}
public HttpConnectionFactory(int allowedTransports) {
this(transportMaskToArray(allowedTransports));
}
public HttpConnectionFactory(int transportPriority[]) {
if (!serviceRecordsLoaded) {
loadServiceBooks(false);
}
transports = transportPriority;
}
public static String getUserAgent() {
StringBuffer sb = new StringBuffer();
sb.append("BlackBerry");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion());
sb.append(" Profile/");
sb.append(System.getProperty("microedition.profiles"));
sb.append(" Configuration/");
sb.append(System.getProperty("microedition.configuration"));
sb.append(" VendorID/");
sb.append(Branding.getVendorId());
return sb.toString();
}
public static String getProfile() {
StringBuffer sb = new StringBuffer();
sb.append("http://www.blackberry.net/go/mobile/profiles/uaprof/");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion().substring(0, 3)); //RDF file format is 4.5.0.rdf (does not include build version)
sb.append(".rdf");
return sb.toString();
}
public HttpConnection getHttpConnection(String pURL) {
return getHttpConnection(pURL, null, null);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers) {
return getHttpConnection(pURL, headers, null);
}
public HttpConnection getHttpConnection(String pURL, byte[] data) {
return getHttpConnection(pURL, null, data);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers, byte[] data) {
if ((pURL.length() > 5) && pURL.startsWith("cod://")) {
return new LocalHttpConnection(pURL);
}
int curIndex = 0;
HttpConnection con = null;
while ((con = tryHttpConnection(pURL, curIndex, headers, data)) == null) {
try {
curIndex = nextTransport(curIndex);
} catch (HttpConnectionFactoryException e) {
e.printStackTrace();
break;
} finally {
}
}
if (con != null) {
setLastTransport(transports[curIndex]);
}
return con;
}
private int nextTransport(int curIndex) throws HttpConnectionFactoryException {
if ((curIndex >= 0) && (curIndex < transports.length - 1)) {
return curIndex + 1;
} else {
throw new HttpConnectionFactoryException("No more transport available.");
}
}
private HttpConnection tryHttpConnection(String pURL, int tIndex, HttpHeaders headers, byte[] data) {
HttpConnection con = null;
OutputStream os = null;
log.debug("Trying " + getTransportName(transports[tIndex]) + "... ");
switch (transports[tIndex]) {
case TRANSPORT_SIM:
try {
con = getSimConnection(pURL, false);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_WIFI:
try {
con = getWifiConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BES:
try {
con = getBesConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BIS:
try {
con = getBisConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_DIRECT_TCP:
try {
con = getTcpConnection(pURL);
} catch (IOException e) {
} finally {
break;
}
case TRANSPORT_WAP2:
try {
con = getWap2Connection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
}
log.debug("con = " + con);
if (con != null) {
try {
log.debug("url = " + con.getURL());
//add headers to connection
if (headers != null) {
int size = headers.size();
for (int i = 0; i < size;) {
String header = headers.getPropertyKey(i);
String value = headers.getPropertyValue(i++);
if (value != null) {
con.setRequestProperty(header, value);
}
}
}
// post data
if (data != null) {
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(data.length));
os = con.openOutputStream();
os.write(data);
} else {
con.setRequestMethod(HttpConnection.GET);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return con;
}
public int getLastTransport() {
return lastTransport;
}
public String getLastTransportName() {
return getTransportName(getLastTransport());
}
private void setLastTransport(int pLastTransport) {
lastTransport = pLastTransport;
}
private HttpConnection getSimConnection(String pURL, boolean mdsSimulatorRunning) throws IOException {
if (DeviceInfo.isSimulator()) {
if (mdsSimulatorRunning) {
return getConnection(pURL, ";deviceside=false", null);
} else {
return getConnection(pURL, ";deviceside=true", null);
}
}
return null;
}
private HttpConnection getBisConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(4 /* CoverageInfo.COVERAGE_BIS_B */)) {
return getConnection(pURL, ";deviceside=false;ConnectionType=mds-public", null);
}
return null;
}
private HttpConnection getBesConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(2 /* CoverageInfo.COVERAGE_MDS */)) {
return getConnection(pURL, ";deviceside=false", null);
}
return null;
}
private HttpConnection getWifiConnection(String pURL) throws IOException {
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
return getConnection(pURL, ";interface=wifi", null);
}
return null;
}
private HttpConnection getWap2Connection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */) && (srWAP2 != null) && (srWAP2.length != 0)) {
return getConnection(pURL, ";deviceside=true;ConnectionUID=", srWAP2[0].getUid());
}
return null;
}
private HttpConnection getTcpConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */)) {
return getConnection(pURL, ";deviceside=true", null);
}
return null;
}
private HttpConnection getConnection(String pURL, String transportExtras1, String transportExtras2) throws IOException {
StringBuffer fullUrl = new StringBuffer();
fullUrl.append(pURL);
if (transportExtras1 != null) {
fullUrl.append(transportExtras1);
}
if (transportExtras2 != null) {
fullUrl.append(transportExtras2);
}
return (HttpConnection) Connector.open(fullUrl.toString());
}
public static void reloadServiceBooks() {
loadServiceBooks(true);
}
private static synchronized void loadServiceBooks(boolean reload) {
if (serviceRecordsLoaded && !reload) {
return;
}
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
Vector mdsVec = new Vector();
Vector bisVec = new Vector();
Vector wap2Vec = new Vector();
Vector wifiVec = new Vector();
if (!serviceRecordsLoaded) {
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
String cid, uid;
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
if ((cid.indexOf("wptcp") != -1) && (uid.indexOf("wap2") != -1) && (uid.indexOf("wifi") == -1) && (uid.indexOf("mms") == -1)) {
wap2Vec.addElement(myRecord);
}
}
}
srWAP2 = new ServiceRecord[wap2Vec.size()];
wap2Vec.copyInto(srWAP2);
wap2Vec.removeAllElements();
wap2Vec = null;
serviceRecordsLoaded = true;
}
}
public static int[] transportMaskToArray(int mask) {
if (mask == 0) {
mask = TRANSPORTS_ANY;
}
int numTransports = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
numTransports++;
}
}
int transports[] = new int[numTransports];
int index = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
transports[index++] = DEFAULT_TRANSPORT_ORDER[i];
}
}
return transports;
}
private static String getTransportName(int transport) {
String tName;
switch (transport) {
case TRANSPORT_WIFI:
tName = "WIFI";
break;
case TRANSPORT_BES:
tName = "BES";
break;
case TRANSPORT_BIS:
tName = "BIS";
break;
case TRANSPORT_DIRECT_TCP:
tName = "TCP";
break;
case TRANSPORT_WAP2:
tName = "WAP2";
break;
case TRANSPORT_SIM:
tName = "SIM";
break;
default:
tName = "UNKNOWN";
break;
}
return tName;
}
}

How to parse xml document in Blackberry?

How can I parse a xml file in Blackberry? Can I have a link or sample code or tutorial?
I've used SAX to process XML responses from a web api and it worked well for me. Check out: http://developerlife.com/tutorials/?p=28
What exactly are you trying to accomplish with XML?
You should have a interface to implement the listener in order to notify your UI thread once parsing is over.
import java.util.Vector;
public interface MediaFeedListner {
public void mediaItemParsed(Vector mObject);
public void exception(java.io.IOException ioe);
}
implement your class with MediaFeedListner and then override the mediaItemParsed(Vector mObject) and exception(java.io.IOException ioe) methoods.
mediaItemParsed() method will have the logic for notifying the UI thread and perform required operations.
Here is the XML parser code.
package com.test.net;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import net.rim.device.api.xml.parsers.ParserConfigurationException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.span.data.MediaObject;
import com.span.utils.FileManager;
public class MediaHandler extends DefaultHandler {
protected static final String TAG_FEED = "feed";
protected static final String TAG_ENTRY = "entry";
protected static final String TAG_TITLE = "title";
protected static final String TAG_MEDIA_GROUP = "group";
protected static final String TAG_MEDIA_CATEGORY = "category";
protected static final String TAG_MEDIA_CONTENT = "content";
protected static final String TAG_MEDIA_DESCRIPTION = "description";
protected static final String TAG_MEDIA_THUMBNAIL = "thumbnail";
protected static final String ATTR_MEDIA_CONTENT= "url";
protected static final String ATTR_MEDIA_THUMBNAIL = "url";
boolean isEntry = false;
boolean isTitle = false;
boolean isCategory = false;
boolean isDescription = false;
boolean isThumbUrl = false;
boolean isMediaUrl = false;
boolean isMediaGroup = false;
String valueTitle = "";
String valueCategory = "";
String valueDescription = "";
String valueThumbnailUrl = "";
String valueMediaUrl = "";
public static Vector mediaObjects = null;
MediaObject _dataObject = null;
MediaFeedListner listner = null;
public MediaHandler(MediaFeedListner listner) {
this.listner = listner;
mediaObjects = new Vector();
}
public void parseXMLString(String xmlString) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new ByteArrayInputStream(xmlString.getBytes()), this);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
//return;
}
if(localName.equals(TAG_ENTRY))
{
_dataObject = new MediaObject();
isEntry = true;
}
if(isEntry) {
if(localName.equalsIgnoreCase(TAG_TITLE)) {
isTitle = true;
}
if(localName.equals(TAG_MEDIA_GROUP))
isMediaGroup = true;
if(isMediaGroup) {
if(localName.equalsIgnoreCase(TAG_MEDIA_CONTENT)) {
valueMediaUrl = attributes.getValue(ATTR_MEDIA_CONTENT);
if(valueMediaUrl != null) {
_dataObject.setMediaUrl(valueMediaUrl);
valueMediaUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_THUMBNAIL)) {
valueThumbnailUrl = attributes.getValue(ATTR_MEDIA_THUMBNAIL);
if(valueThumbnailUrl != null) {
_dataObject.setMediaThumb(valueThumbnailUrl);
valueThumbnailUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_DESCRIPTION)) {
isDescription = true;
}
if(localName.equalsIgnoreCase(TAG_MEDIA_CATEGORY)) {
isCategory = true;
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(isTitle){
valueTitle = new String(ch, start, length);
_dataObject.setMediaTitle(valueTitle);
System.out.println("Title value " + valueTitle);
valueTitle = "";
}
if(isCategory){
valueCategory = new String(ch, start, length);
_dataObject.setMediaCategory(valueCategory);
System.out.println("category value " + valueCategory);
valueCategory = "";
}
if(isDescription){
valueDescription = new String(ch, start, length);
_dataObject.setMediaDesc(valueDescription);
System.out.println("category value " + valueDescription);
valueDescription = "";
}
}
public void endElement(String uri, String localName, String name) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
listner.mediaItemParsed(mediaObjects);
printMediaInfo(mediaObjects);
}
if(localName.equalsIgnoreCase(TAG_ENTRY)) {
isEntry = false;
isTitle = false;
isCategory = false;
isDescription = false;
mediaObjects.addElement(_dataObject);
}
}
public static void printMediaInfo(Vector v){
int length = v.size();
for(int i = 0 ; i <length ; i++){
MediaObject mediaObj = (MediaObject) v.elementAt(i);
FileManager.getInstance().writeLog("Title: " + mediaObj.getMediaTitle());
FileManager.getInstance().writeLog("Category: " + mediaObj.getMediaCategory());
FileManager.getInstance().writeLog("Desc: " + mediaObj.getMediaDesc());
FileManager.getInstance().writeLog("URL: " + mediaObj.getMediaUrl());
FileManager.getInstance().writeLog("Thumb: " + mediaObj.getMediaThumb());
FileManager.getInstance().writeLog("Fav count: " + mediaObj.getMediaFavCount());
FileManager.getInstance().writeLog("View Count: " + mediaObj.getMediaViewCount());
FileManager.getInstance().writeLog("Ratings: " + mediaObj.getMediaRating());
FileManager.getInstance().writeLog("============================================");
}
}
}
Its done.

Resources