selenium webdriver - how to handle ajax calls - selenium-webdriver

I have been reading about how to handle AJAX in Selenium webdriver. There are a lot of solutions. Is there one best and correct solution?
The solutions I have read about so far are:
1) Using thread sleep
2) waitFor method
3) ExpectedCondition
4) FluentWait
5) PresenceOfElementLocated
Thanks!

The reliable solution to handle ajax components(as used in my case) is to wait for the element to be visible on the page using waitUntil() API call of webdriver.
Otherwise threadsleep() like solution is not at all recommended to handle Ajax.

I have used this and it itself waits works fine.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thanks try it.

If you're using jQuery, this is what I recommend. You can control exactly how often polling happens.
// poll every 1/3 second for 3 seconds
int timeout = 3; // seconds
int pollFreq = 3; // times per second
WebDriverWait wait = new WebDriverWait(driver, timeout, 1000/pollFreq);
// to be safe, test (driver instanceof JavascriptExecutor) here
JavascriptExecutor executor = ((JavascriptExecutor) driver);
// Check to see if jQuery is available first
Boolean hasJquery = (Boolean) executor.executeScript("return !!window.jQuery");
Boolean hasActive = (Boolean) executor.executeScript("return typeof window.jQuery.active === \"number\"");
if (hasJquery && hasActive) {
// Wait for JS AJAX calls to complete...
wait.until((ExpectedCondition<Boolean>) driver -> (Boolean) executor
.executeScript("return window.jQuery.active === 0"));
// JS AJAX calls completed.
// Good idea to add a timing report here for troubleshooting.
}
// else jQuery/active-prop not available, continue

You might want to try the Apache Http Client if you want to perform make ajax requests from your test. Here is some Groovy code that does this. Chances are not high that you are using Groovy, but this should still be informative regarding Get & Post in general with the client.
import groovy.util.Expando
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.methods.GetMethod
import java.io.BufferedReader
import java.io.InputStreamReader
import org.apache.commons.httpclient.Header
import java.net.URLDecoder
import com.auto.utils.crypto.Crypto
class ClientHttps {
private HttpClient client = null
private BufferedReader br = null
private String cookieString = ""
private crypto = new Crypto()
def log
public ClientHttps(log) {
this.log = log
client = new HttpClient();
client.getParams().setParameter("http.useragent", "Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2")
}
public Expando get(String url) {
def startTime = System.nanoTime()
GetMethod method = new GetMethod(url)
Expando returnData = new Expando()
try {
log.info("cookieString = " + cookieString)
method.addRequestHeader("Cookie", cookieString)
method.addRequestHeader("Accept", "application/json")
int returnCode = client.executeMethod(method)
log.info("returnCode = " + returnCode)
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Get method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_PERMANENTLY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine;
while(((readLine = br.readLine()) != null)) {
log.info(readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
returnData.setProperty(it.getName(), it.getValue())
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Get took = " + seconds + " seconds (Get url = " + url + ")")
return returnData;
} catch (Exception e) {
log.error(e.message, e)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
public Expando post(Expando postData) {
def startTime = System.nanoTime()
PostMethod method = new PostMethod(postData.getProperty("url"))
postData.getProperty("params").each() {method.addParameter(it.key, it.value)}
Expando returnData = new Expando()
try {
int returnCode = client.executeMethod(method)
log.info(returnCode)
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Post method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_TEMPORARILY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine
while(((readLine = br.readLine()) != null)) {
log.info("Response Data = " + readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
try {
returnData.setProperty(it.value.split("=")[0], it.value.split("=")[1])
}
catch (Exception exc) {
log.info("Could not split on equals sign = " + it.value)
}
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Post took = " + seconds + " seconds (Post url = " + postData.getProperty("url") + ")")
return returnData
} catch (Exception exc) {
log.info(exc.message, exc)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
}

Related

How to call https api from wpf

I'm trying to call the https API from the WPF application but i'm getting this error:
InnerException = {"The underlying connection was closed: An unexpected
error occurred on a send."} Message = "An error occurred while sending
the request."
Can anyone help me what exactly the problem is?
private static readonly string apiURL =
"https://api.totalsynergy.com/api/v2/Profile/Index";
private async Task<bool> GetAuth(string accessToken)
{
try
{
HttpClient hc = new HttpClient();
HttpResponseMessage hpm = await hc.GetAsync(apiURL);
if (hpm.IsSuccessStatusCode)
{
var res = await hpm.Content.ReadAsAsync<Organization>();
}
return boolValue;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return boolValue;
}
}
When is HTTPS, connection requires some protocols.
In my example I have a API URL that I call and can send some information and receive the response in JSON. You can adapt this to your problem:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//get OS version
var query = "SELECT version FROM Win32_OperatingSystem";
var searcher = new ManagementObjectSearcher(query);
var info = searcher.Get().Cast<ManagementObject>().FirstOrDefault();
string version = info.Properties["Version"].Value.ToString();
int majorVersion = Int32.Parse(version.Substring(0, version.IndexOf(".")));
//OS version is windows xp or older
if (majorVersion < 6)
{
//tls 1.0
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192;
}
else
{
//tls 1.1 or tls 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
}
//url to send data
string url = **YOUR URL**
//create request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = 240000;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = **REQUEST METHOd GET/POST**;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
//convert to byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(**Text to send or empty**);
//specify content of request - this example is in JSON
request.ContentType = "application/json";
if (requestMethod != RequestMethods.GET)
{
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
//send
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (var readers = new StreamReader(response.GetResponseStream()))
{
return result = readers.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
finally
{
request.Abort();
}

Extracting text inside body of mail using javamail API stopping after first iteration

I've searched for hours and tried everything to fix this code. I've been working with the example below and after updating appropriate variables this works fine through till the end of processing the first email. It seems to pause indefinitely. I had to alter code at (//check if the content is an inline image) as variables appear to need declaration before they were used but have not changed anything apart from that. Any help before I loose my mind will be much appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original code at https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code below... (output below that)
package com.mail.coder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail2 {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect("mail.DOMAIN.com", "USERNAME#DOMAIN.com", "PASS");
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call method writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
**int i;
byte[] bArray = new byte[x.available()];**
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
i = 0;
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output
messages.length---5
---------------------------------
This is the message envelope
---------------------------
FROM: Jack Frost <sender#gmail.com>
TO: recipient#domain.com
SUBJECT: another email
----------------------------
CONTENT-TYPE: multipart/alternative; boundary="000000000000096c73056991868c"
This is a Multipart
---------------------------
----------------------------
CONTENT-TYPE: text/plain; charset="UTF-8"
This is plain text
---------------------------
testing
----------------------------
CONTENT-TYPE: text/html; charset="UTF-8"
This is a string
---------------------------
<div dir="ltr">testing</div>

javamail also extract attachments of encapsulated message Content-Type: message/rfc822

I want to extract ALL the attachments of an .eml message which is encapsulated (Content-Type: message/rfc822) in the message InputStream
InputStream is = new FileInputStream(Path);
MimeMessage mime = new MimeMessage(null, is);
private String getAttachments(p) throws
MessagingException, IOException {
if ( p.isMimeType("multipart/*")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) {
file_name = part.getFileName();
part.saveFile(Attachments_Folder + "\\" + MailFileName + "_" + file_name);
}
}
}
}
is.close()
Also, when the Content-Type is message/rfc822, the part.getFileName() is null and therefore the saved file has no extension and I don't know how to get this one.
MIME does not require every body part to have a file name. If the part doesn't have a file name and you need one, you'll have to make one up yourself.
Note also that you want to be very careful when using a file name that you get in an email message. It could be something unexpected or malicious, e.g., containing "../../../../../whatever".
I did it by adding a new filename to the included message as an .eml file and a recursion with the included message
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.io.FileInputStream.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Part;
import javax.mail.Multipart;
getAttachments(Path) ;
//function
private String getAttachments(path) throws
MessagingException, IOException {
InputStream is = new FileInputStream(path);
MimeMessage p = new MimeMessage(null, is);
if ( p.isMimeType("multipart/*")) {
// if (contentType.contains("multipart")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart)multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
file_name = part.contentType == "message/rfc822" ? "message_inclus" + partCount + ".eml" : MimeUtility.decodeText(part.getFileName());
exportedpath = Attachments_Folder + "/" + MailFileName + "_" + file_name;
part.saveFile(exportedpath);
if ( part.contentType == "message/rfc822" ) {
getAttachments(exportedpath)
}
}
}
}
is.close()
return 1
}
Better use org.apache.commons.mail.util.MimeMessageParser.
MimeMessageParser has as method called hasAttachments() which
returns true , if message has an attachments.
Then loop through the all attachments and check for content-type
message/rfc822 from getContentType().
Create new MimeMessage with the DataSource InputStream
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
Finally you have MimeMessage.
Maven Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>RELEASE</version>
</dependency>
Code Sample:
public void readEmails() throws Exception{
// mail server connection parameters
String host = "host";
String user = "username";
String pwd = "pwd";
// connect to my pop3 inbox
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, pwd);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// get the list of inbox messages
Message[] messages = inbox.getMessages();
if (messages.length == 0) System.out.println("No messages found.");
for (int i = 0; i < messages.length; i++) {
// stop after listing ten messages
if (i > 10) {
System.exit(0);
inbox.close(true);
store.close();
}
final MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) messages[i]);
mimeMessageParser.parse();
if (mimeMessageParser.hasAttachments()) {
List<DataSource> attachmentList = mimeMessageParser.getAttachmentList();
System.out.println("Number of attachments: " +attachmentList.size());
for (DataSource attachment:attachmentList
) {
System.out.println("Name: "+attachment.getName()+" Content Type: "+attachment.getContentType());
if (attachment.getContentType().equals("message/rfc822")) {
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
System.out.println("Subject of the attached failure Mail:" + message.getSubject());
}
}
}
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
System.out.println("Sent Date : " + messages[i].getSentDate());
System.out.println();
}
inbox.close(true);
store.close();
}

I get an transformClassesWithRealmTransformerForDebug error

This is the error that I get:
Error:
Execution failed for task ':passenger:transformClassesWithRealmTransformerForDebug'.
javassist.CannotCompileException: updateVehicle (Landroid/content/Context;Ljava/lang/Integer;Lnl/hgrams/passenger/model/Vehicle;Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Lnl/hgrams/passenger/interfaces/JsonCallback;)V in nl.hgrams.passenger.model.UserVehicle: failed to resolve types
Now I seen that the latest versions of Realm do support having functions inside the realmObject.
I have this function inside that causes the crash:
public void updateVehicle(Context context, Integer userID, Vehicle newVehicle, Integer vclass, String newCountry, String newLicense, String newImage, List<MileageRates> mileageRates, final JsonCallback jsonCallback) {
try{
JSONObject params = createJsonForUpdate(context,newVehicle, vclass, newCountry, newLicense, newImage, mileageRates);
Log.i("","vehicle params is:" + params.toString());
WSCalls.sendData(Request.Method.POST, Constants.API_ENDPOINT + "/users/" + userID + "/vehicles/" + id + "/update", params , context, null, true, new JsonCallback() {
#Override
public void onResponse(JSONObject jsonObject, VolleyError error, String errorMsg) {
if(jsonCallback != null)
jsonCallback.onResponse(jsonObject,error,errorMsg);
}
});
}catch (Exception e){
Log.e("","error updating vehicle:" + e.getMessage());
}
}
IF I comment out WScall.sendData, then it will work.
This is the method:
public static void sendData(final Integer type , final String url, final JSONObject params, final Context context, final View loader, boolean hasAllURL , final JsonCallback listener){
String URL = Constants.API_ENDPOINT + url;
if(hasAllURL){
URL = url;
}
final String URL2 = URL;
Log.i(TAG, "test offline sendData - url:: " + URL);
if(params != null) {
Log.i(TAG, "test offline sendData - params: " + params.toString());
}
JsonObjectRequest jr = new JsonObjectRequest(type, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "sendData Response: " + response.toString());
Utils.logWSResponse("POST", URL2, 200, response.toString(), header);
try{
if(Utils.WSValidator(response)){
if(loader!= null)
loader.setVisibility(View.GONE);
if(listener != null)
listener.onResponse(response, null, null);
}else{
if(listener != null)
listener.onResponse(response,null, null);
Log.i("","test offline data:" + response.toString());
Utils.appendLog("send data response not VALID",true);
}
}catch (Exception e){
Utils.appendLog("send data error: " + e.getMessage(),true);
Log.e(TAG, "JsonException: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
if(loader!= null)
loader.setVisibility(View.GONE);
if(error != null && error.networkResponse != null) {
Utils.appendLog("WSCALL send data done, ERROR stop STATUS CODE" + error.networkResponse.statusCode, true);
json = new String(error.networkResponse.data);
json = trimMessage(json, "message");
if (json != null) {
Utils.logWSResponse("POST", URL2, error.networkResponse.statusCode, json, header);
}
Log.i(TAG, "checkout valid send data Volley error response: " + json);
if(error.networkResponse.statusCode == 401 && PSLocationCenter.getInstance().pref.getAuthenticationToken() != null){
PSLocationCenter.getInstance().pref.setFbConnected(context, false);
if(PSSocialService.getInstance().fbSession != null){
PSSocialService.getInstance().fbSession.closeAndClearTokenInformation();
}
PSUserService.getInstance(context).finishLogOut();
return;
}
}
if(listener != null)
listener.onResponse(null, error, json);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
PassengerPreferencesManager pref = new PassengerPreferencesManager(context);
if(pref.getAuthenticationToken() != null){
return getHeaderData(pref, context);
}else{
return super.getHeaders();
}
}
};
if (Utils.networkIsAvailable( context)) {
try{
header = jr.getHeaders().toString();
Utils.logWSRequest("POST", URL, params.toString() ,header);
}catch (Exception e){
Log.e("","error volley: " + e.getMessage());
}
jr.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, 1));
PSLocationCenter.getInstance().mRequestQueue.add(jr);
}
else {
if(loader!= null)
loader.setVisibility(View.GONE);
Log.i(TAG, "sendData - no internet");
AlertDialog.show(context, "", context.getString(R.string.no_internet), context.getString(R.string.OK), null);
}
}
Can this be fixed? or it does not support that method cause of nonrealm objects in it? I tried to add a nonrealm object inside and it worked.
Also, Another question. can I add inside my realmObject Integers that I don't want to be added to the db. Values that I use in functions, so that I do not need to call a realm transaction every time I use them?
I have the URL like this:
Constants.API_ENDPOINT + "/users/" + userID + "/vehicles/" + id + "/update"
If I set getId() instead of simply the variable, it works

Get IMSI from the SIM using codename1

I need to get the IMSI (International
Mobile Subsriber Identity) stored in the SIM card using codename1. Also in the case of dual or tri SIM phones, i need to get the IMSI for each SIM. Please, How do i get it?
Display.getMsisdn() will work for some devices but most don't allow accessing that information. For more information you can just use a native interface if you can access it that way.
Another way to get IMSI for dual Sim device:
Try this .. its working for me. Idea is to call service for iphonesubinfo function#3. you will get output as parcel value thats why I use getNumberFromParcel to extract number.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by Apipas on 6/4/15.
*/
public class SimUtil {
public static String getIMSI_1() {
String imsiParcel = runCommand("service call iphonesubinfo 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_1:" + imsi);
return imsi;
}
public static String getIMSI_2() {
String imsiParcel = runCommand("service call iphonesubinfo2 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_2:" + imsi);
return imsi;
}
public static String runCommand(String src) {
try {
Process process = Runtime.getRuntime().exec(src);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[2048];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
Log.e("apipas", "IOException:" + e.getMessage());
return null;
} catch (InterruptedException e) {
Log.e("apipas", "InterruptedException:" + e.getMessage());
return null;
}
}
public static String getNumberFromParcel(String str) {
String res = "";
if (str != null && str.length() > 0) {
String lines[] = str.split("\n");
for (String line : lines) {
if (line == null || line.length() == 0)
continue;
String content[] = line.split("'");
if (content.length > 1) {
res += content[1].replace(".", "");
}
}
} else return "NA";
return res;
}
}
Then call these static methods like:
String imsi1 = SimUtil.getIMSI_1();
String imsi2 = SimUtil.getIMSI_2();
You'd need to set this permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Resources