I want to integrate QuickBooks api into our android application.
Below link is for Java Web Application but I want to this OauthHelper class in my android application.
https://github.com/IntuitDeveloperRelations/QuickbooksV3API-Java/blob/master/QuickbooksV3API/src/main/java/com/intuit/utils/OauthHelper.java
I also saw developer site of Intuit but it does not help,
https://intuitpartnerplatform.lc.intuit.com/questions/825445-can-t-find-com-intuit-ia-connection-oauthhelper-class
Is there is a new way to do it or any latest jar file which contain OauthHelper class?
JAR File
You have to add this jar ipp-v3-java-devkit-2.3.2-jar-with-dependencies, you can download from this link.
OauthHelper Class
public class OauthHelper {
public static String REQUEST_TOKEN_URL;
public static String ACCESS_TOKEN_URL;
public static String AUTHORIZE_URL;
public OauthHelper() {
REQUEST_TOKEN_URL = Constants.OAUTH_URL + "/oauth/v1/get_request_token";
ACCESS_TOKEN_URL = Constants.OAUTH_URL + "/oauth/v1/get_access_token";
AUTHORIZE_URL = Constants.APPCENTER_URL + "/Connect/Begin";
}
public void getDynamicConsumer() {
try {
final String apptoken = Constants.APP_TOKEN;
final URL url = new URL(Constants.OAUTH_URL
+ "/oauth/v1/create_consumer?appToken=" + apptoken);
final HttpURLConnection httpconnection = (HttpURLConnection) url
.openConnection();
httpconnection.connect();
StringBuffer responseBody = null;
int read = 0;
final byte buffer[] = new byte[8192];
String consumerret = "";
String consumerkeytoken = "";
String consumerkeysecret = "";
try {
final InputStream responseBodyStream = httpconnection
.getInputStream();
responseBody = new StringBuffer();
while ((read = responseBodyStream.read(buffer)) != -1) {
responseBody.append(new String(buffer, 0, read));
}
responseBodyStream.close();
consumerret = responseBody.toString();
final String[] consumerkey = consumerret.split("&");
for (int i = 0; i < consumerkey.length; i++) {
final String[] currentElements = consumerkey[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
consumerkeytoken = currentElements[1];
} else if (currentElements[0]
.equalsIgnoreCase("oauth_token_secret")) {
consumerkeysecret = currentElements[1];
}
}
} catch (Exception ex1) {
final int httpRespCode = httpconnection.getResponseCode();
try {
final InputStream es = httpconnection.getErrorStream();
final StringBuffer errorBody = new StringBuffer();
while ((read = es.read(buffer)) != -1) {
errorBody.append(new String(buffer, 0, read));
}
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
} catch (Exception ex3) {
ex3.printStackTrace();
}
}
public Map<String, String> getRequestTokenSignPost() {
String authURL = null;
OAuthProvider provider = createProvider();
String consumerkey = Constants.CONSUMER_KEY;
String consumersecret = Constants.CONSUMER_SECRET;
String callback_url = Constants.CALLBACK_URL;// WebUtils.OAUTH_CALLBACK_URL;
OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey,
consumersecret);
try {
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback",
URLEncoder.encode(callback_url, "UTF-8"));
ouathconsumer.setAdditionalParameters(additionalParams);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String requestret = "";
String requestToken = "";
String requestTokenSecret = "";
try {
String signedRequestTokenUrl = ouathconsumer
.sign(REQUEST_TOKEN_URL);
URL url;
url = new URL(signedRequestTokenUrl);
HttpURLConnection httpconnection = (HttpURLConnection) url
.openConnection();
httpconnection.setRequestMethod("GET");
httpconnection
.setRequestProperty("Content-type", "application/xml");
httpconnection.setRequestProperty("Content-Length", "0");
if (httpconnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(
httpconnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
requestret = sb.toString();
}
String[] requestTokenSections = requestret.split("&");
for (int i = 0; i < requestTokenSections.length; i++) {
String[] currentElements = requestTokenSections[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
requestToken = currentElements[1];
} else if (currentElements[0]
.equalsIgnoreCase("oauth_token_secret")) {
requestTokenSecret = currentElements[1];
}
}
Map<String, String> requesttokenmap = new HashMap<String, String>();
try {
authURL = provider.retrieveRequestToken(ouathconsumer,
callback_url);
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
}
ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(),
ouathconsumer.getTokenSecret());
requesttokenmap.put("requestToken", requestToken);
requesttokenmap.put("requestTokenSecret", requestTokenSecret);
requesttokenmap.put("authURL", authURL);
return requesttokenmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static OAuthProvider createProvider() {
OAuthProvider provider = new DefaultOAuthProvider(
OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL,
OauthHelper.AUTHORIZE_URL);
return provider;
}
public String getAuthorizeURL(String requestToken, String requestTokenSecret) {
String authorizeURL = "";
try {
authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
} catch (Exception e) {
e.printStackTrace();
}
return authorizeURL;
}
public Map<String, String> getAccessToken(String verifierCode,
String requestToken, String requestTokenSecret) {
String consumerkey = Constants.CONSUMER_KEY;
String consumersecret = Constants.CONSUMER_SECRET;
String accessToken = "";
String accessTokenSecret = "";
try {
OAuthConsumer consumer = new DefaultOAuthConsumer(consumerkey,
consumersecret);
consumer.setTokenWithSecret(requestToken, requestTokenSecret);
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback", "oob");
additionalParams.put("oauth_verifier", verifierCode);
consumer.setAdditionalParameters(additionalParams);
String signedURL = consumer.sign(ACCESS_TOKEN_URL);
URL url = new URL(signedURL);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-type", "application/xml");
urlConnection.setRequestProperty("Content-Length", "0");
String accesstokenresponse = "";
if (urlConnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
accesstokenresponse = sb.toString();
}
if (accesstokenresponse != null) {
String[] responseElements = accesstokenresponse.split("&");
if (responseElements.length > 1) {
accessToken = responseElements[1].split("=")[1];
accessTokenSecret = responseElements[0].split("=")[1];
Map<String, String> accesstokenmap = new HashMap<String, String>();
accesstokenmap.put("accessToken", accessToken);
accesstokenmap.put("accessTokenSecret", accessTokenSecret);
return accesstokenmap;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Constants Class
public class Constants {
public static final String APP_TOKEN = ""; // First three credentials are from **Production** part not from **Development** part
public static final String CONSUMER_KEY = "";
public static final String CONSUMER_SECRET = "";
public static final String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static final String AUTH_URL = "https://appcenter.intuit.com/Connect/Begin";
public static final String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static final String OAUTH_CALLBACK_SCHEME = "oauthflow-quickbooks";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
+ OAUTH_CALLBACK_HOST;
public static final String PREFERENCE_NAME = "quickbooks";
public static String OAUTH_URL = "https://oauth.intuit.com";
public static String APPCENTER_URL = "https://appcenter.intuit.com";
}
Manifest file
Add following intent filter to activity when login is initiated.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="oauthflow-quickbooks" />
</intent-filter>
Related
I just implemented Xamarin.Auth on UWP, and I have a weird problem.
I begin by creating my OAuth object :
public class OAuth
{
private Account account;
private AccountStore store;
public string Scope;
public string AuthorizeUrl;
public string AccessTokenUrl;
public string UserInfoUrl;
string clientId;
string clientSecret;
string redirectUri;
private bool isUsingNativeUI;
private Func<JObject, User> OAuthParser;
private Action<User> OnCompleted;
private Action<string> OnError;
public OAuth()
{
account = null;
store = null;
Scope = "";
AuthorizeUrl = "";
AccessTokenUrl = "";
UserInfoUrl = "";
clientId = "";
clientSecret = null;
redirectUri = "";
}
public OAuth Facebook()
{
// These values do not need changing
Scope = "email";
AuthorizeUrl = "https://www.facebook.com/v2.8/dialog/oauth";
AccessTokenUrl = "https://graph.facebook.com/oauth/access_token";
UserInfoUrl = "https://graph.facebook.com/me?fields=email,name,gender,picture";
clientId = "xxxx";
clientSecret = "xxxxx";
redirectUri = "http://www.facebook.com/connect/login_success.html";
isUsingNativeUI = false;
OAuthParser = ParseFacebookResponse;
return this;
}
public OAuth GooglePlus()
{
// These values do not need changing
Scope = "https://www.googleapis.com/auth/userinfo.email";
AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth";
AccessTokenUrl = "https://www.googleapis.com/oauth2/v4/token";
UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
clientId = "xxxxx";
redirectUri = "xxxxxx";
isUsingNativeUI = true;
OAuthParser = ParseGooglePlusResponse;
return this;
}
public OAuth2Authenticator Authenticator(Action<User> onCompleted, Action<string> onError)
{
OAuth2Authenticator authenticator = new OAuth2Authenticator(
clientId,
clientSecret,
Scope,
new Uri(AuthorizeUrl),
new Uri(redirectUri),
new Uri(AccessTokenUrl),
null,
isUsingNativeUI);
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
OnCompleted = onCompleted;
OnError = onError;
return authenticator;
}
private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
User user = null;
try
{
OAuth2Authenticator OAuth2Authenticator = sender as OAuth2Authenticator;
if (OAuth2Authenticator != null)
{
OAuth2Authenticator.Completed -= OnAuthCompleted;
OAuth2Authenticator.Error -= OnAuthError;
}
//User user = null;
if (e.IsAuthenticated)
{
var request = new OAuth2Request("GET", new Uri(UserInfoUrl), null, e.Account);
var response = await request.GetResponseAsync();
if (response != null)
{
user = OAuthParser(JObject.Parse(await response.GetResponseTextAsync()));
}
if (account != null)
{
store.Delete(account, App.AppName);
}
await store.SaveAsync(account = e.Account, App.AppName);
}
} catch (Exception ex) {
Debug.WriteLine(ex);
}
(Application.Current.MainPage as LoginPage).OAuthCompleted(user);
}
private void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
{
OAuth2Authenticator OAuth2Authenticator = sender as OAuth2Authenticator;
if (OAuth2Authenticator != null)
{
OAuth2Authenticator.Completed -= OnAuthCompleted;
OAuth2Authenticator.Error -= OnAuthError;
}
(Application.Current.MainPage as LoginPage).OAuthError("Authentication error: " + e.Message);
}
private static User ParseGooglePlusResponse(JObject jobject)
{
try
{
User user = new User()
{
Email = jobject["email"].ToString(),
Pseudo = jobject["name"].ToString(),
Firstname = jobject["given_name"].ToString(),
Surname = jobject["family_name"].ToString(),
Image = jobject["picture"].ToString(),
Password = "girafe"
};
return user;
}
catch (Exception e)
{ Debug.WriteLine(e.ToString()); }
return null;
}
private static User ParseFacebookResponse(JObject jobject)
{
try
{
Debug.WriteLine(jobject);
User user = new User()
{
Email = jobject["email"].ToString(),
Pseudo = jobject["name"].ToString(),
Image = jobject["picture"]["data"]["url"].ToString(),
Password = "girafe"
};
return user;
}
catch (Exception e)
{ Debug.WriteLine(e.ToString()); }
return null;
}
}
And I use it like that:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage, INotifyPropertyChanged
{
private OAuth OAuthService;
private OAuthLoginPresenter Presenter;
// ...
private void FacebookAuthConnection()
{
AuthenticationState.Authenticator = OAuthService.Facebook().Authenticator(OAuthCompleted, OAuthError);
Presenter.Login(AuthenticationState.Authenticator);
}
private void GooglePlusAuthConnection()
{
AuthenticationState.Authenticator = OAuthService.GooglePlus().Authenticator(OAuthCompleted, OAuthError);
Presenter.Login(AuthenticationState.Authenticator);
}
// ...
}
On Android, either if isUsingNativeUI is set to true or false, after I connect myself, the webview/oauth get closed. Over UWP however, it doesn't work when isUsingNativeUI is set to true, the webview/oauth don't close, so I'm navigating on google and I am not able to come back on the app (UWP Desktop)...
Do you have any idea?
In the last DotNetOpenAuth package, GoogleClient extends OpenIdClient, Someone knows where can i find implementation of google Oauth2 which extends DotNetOpenAuth OAuth2Client?
From OAuth2 and DotNetOpenAuth - implementing Google custom client
public class GoogleOAuth2Client : OAuth2Client
{
#region Constants and Fields
/// <summary>
/// The authorization endpoint.
/// </summary>
private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth";
/// <summary>
/// The token endpoint.
/// </summary>
private const string TokenEndpoint = "https://accounts.google.com/o/oauth2/token";
/// <summary>
/// The _app id.
/// </summary>
private readonly string _clientId;
/// <summary>
/// The _app secret.
/// </summary>
private readonly string _clientSecret;
#endregion
public const string ProviderAppendix = "__provider__=google";
public GoogleOAuth2Client(string clientId, string clientSecret)
: base("google")
{
if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException("clientId");
if (string.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException("clientSecret");
this._clientId = clientId;
this._clientSecret = clientSecret;
}
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
StringBuilder serviceUrl = new StringBuilder();
serviceUrl.AppendFormat("{0}?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile", AuthorizationEndpoint);
serviceUrl.Append("&state=google");
serviceUrl.AppendFormat("&redirect_uri={0}", returnUrl.ToString().ToLower());
serviceUrl.Append("&response_type=code");
serviceUrl.AppendFormat("&client_id={0}", _clientId);
return new Uri(serviceUrl.ToString());
}
protected override IDictionary<string, string> GetUserData(string accessToken)
{
var client = new RestClient("https://www.googleapis.com");
var request = new RestRequest(String.Format("/oauth2/v1/userinfo?access_token={0}", accessToken), Method.GET);
IDictionary<String, String> extraData = new Dictionary<String, String>();
var response = client.Execute(request);
if (null != response.ErrorException)
{
return null;
}
else
{
try
{
var json = JObject.Parse(response.Content);
string firstName = (string)json["given_name"];
string lastName = (string)json["family_name"];
string emailAddress = (string)json["email"];
string id = (string)json["id"];
extraData = new Dictionary<String, String>
{
{"accesstoken", accessToken},
{"name", String.Format("{0} {1}", firstName, lastName)},
{"firstname", firstName},
{"lastname", lastName},
{"email", emailAddress},
{"id", id}
};
}
catch (Exception ex)
{
Ccl.Log.Logging.Error("Error requesting OAuth user data from Google", ex);
return null;
}
return extraData;
}
}
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
StringBuilder postData = new StringBuilder();
postData.AppendFormat("client_id={0}", this._clientId);
postData.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(returnUrl.ToString().ToLower()));
postData.AppendFormat("&client_secret={0}", this._clientSecret);
postData.AppendFormat("&grant_type={0}", "authorization_code");
postData.AppendFormat("&code={0}", authorizationCode);
string response = "";
string accessToken = "";
var webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream s = webRequest.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(postData.ToString());
}
using (WebResponse webResponse = webRequest.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
response = reader.ReadToEnd();
}
}
var json = JObject.Parse(response);
accessToken = (string)json["access_token"];
}
catch (Exception ex)
{
Ccl.Log.Logging.Error("Error requesting OAuth access token from Google", ex);
return null;
}
return accessToken;
}
public override AuthenticationResult VerifyAuthentication(HttpContextBase context, Uri returnPageUrl)
{
string code = context.Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
return AuthenticationResult.Failed;
}
string accessToken = this.QueryAccessToken(returnPageUrl, code);
if (accessToken == null)
{
return AuthenticationResult.Failed;
}
IDictionary<string, string> userData = this.GetUserData(accessToken);
if (userData == null)
{
return AuthenticationResult.Failed;
}
string id = userData["id"];
string name;
// Some oAuth providers do not return value for the 'username' attribute.
// In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id'
if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name))
{
name = id;
}
// add the access token to the user data dictionary just in case page developers want to use it
userData["accesstoken"] = accessToken;
return new AuthenticationResult(
isSuccessful: true, provider: this.ProviderName, providerUserId: id, userName: name, extraData: userData);
}
}
Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.
I am working on an email client that will connect to Gmail mailbox and retrieve a specific email.
Now i can connect to my mailbox and can retrieve part of the emails not all of it and no matter how large is my buffer still i get only 1400 char from my email and then Null for the rest of the mail body.
You can find a screen shot for the email body in this link
http://www.elzouhery.com/Mail%20Snapshot.png
Thanks in Advance
EDIT
See below the Full Code
static void Main(string[] args)
{
TcpIMAP imap = ConnectToEmail();
Console.WriteLine("Total Messages " + imap.MailCount());
Console.WriteLine("Total Unread Messages " + imap.MailUnreadCount());
Console.WriteLine("******************************************************");
imap.SelectInbox();
StreamWriter writer = null;
int mailCount = imap.MailCount();
var mailSize = string.Empty;
var content = string.Empty;
var subject = string.Empty;
for (int i = 1; i < mailCount; i++)
{
try
{
writer = new StreamWriter(#"c:\Mails\" + i + ".txt", true);
content = imap.GetMessage(i).ToString();
writer.Write(content);
writer.Close();
}
catch(Exception ex)
{
writer.Write(content);
Console.Write(ex.Message);
writer.Close();
}
}
}
private static TcpIMAP ConnectToEmail()
{
string host = "imap.gmail.com";
string username = "************";
string password = "************";
TcpIMAP imap = new TcpIMAP();
imap.Connect(host, 993);
imap.AuthenticateUser(username, password);
return imap;
}
public static string GetMailSubject(string Header)
{
var headerLines = Header.Split(Environment.NewLine.ToCharArray());
foreach (var line in headerLines)
{
if (line.IndexOf("Subject") > -1)
{
return line.Replace("Subject: ", "");
}
}
return "";
}
/***************************************************/
class TcpIMAP
{
private TcpClient _imapClient;
private Stream _imapNs;
private StreamWriter _imapSw;
private StreamReader _imapSr;
public TcpIMAP()
{
}
public TcpIMAP(string hostname, int port)
{
InitializeConnection(hostname, port);
}
public void Connect(string hostname, int port)
{
InitializeConnection(hostname, port);
}
private void InitializeConnection(string hostname, int port)
{
try
{
_imapClient = new TcpClient(hostname, port);
System.Net.Security.SslStream sslstream = new System.Net.Security.SslStream(_imapClient.GetStream());
sslstream.AuthenticateAsClient("imap.gmail.com");
_imapNs = sslstream;
_imapSw = new StreamWriter(_imapNs);
_imapSr = new StreamReader(_imapNs);
Console.WriteLine("*** Connected ***");
Response();
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
public void AuthenticateUser(string username, string password)
{
_imapSw.WriteLine("$ LOGIN " + username + " " + password);
_imapSw.Flush();
Response();
}
public int MailCount()
{
_imapSw.WriteLine("$ STATUS INBOX (messages)");
_imapSw.Flush();
string res = Response();
Match m = Regex.Match(res, "[0-9]*[0-9]");
return Convert.ToInt32(m.ToString());
}
public int MailUnreadCount()
{
_imapSw.WriteLine("$ STATUS INBOX (unseen)");
_imapSw.Flush();
string res = Response();
Match m = Regex.Match(res, "[0-9]*[0-9]");
return Convert.ToInt32(m.ToString());
}
public string SelectInbox()
{
_imapSw.WriteLine("$ SELECT INBOX");
_imapSw.Flush();
return Response();
}
public object GetMessageHeaders(int index)
{
_imapSw.WriteLine("$ FETCH " + index + " (body[header.fields (from subject date)])");
_imapSw.Flush();
return Response();
}
public object GetMessage(int index)
{
_imapSw.WriteLine("$ FETCH " + index + " BODY.PEEK[]");
_imapSw.Flush();
return Response();
}
private string Response()
{
byte[] data = new byte[_imapClient.ReceiveBufferSize];
int ret = _imapNs.Read(data, 0, data.Length);
string output = Encoding.ASCII.GetString(data).TrimEnd().Replace("\0", "");
return output;
}
public void Disconnect()
{
_imapSw.WriteLine("$ LOGOUT");
_imapSw.Flush();
_imapClient.Close();
}
public string SendCommand(string command)
{
_imapSw.WriteLine("$ " + command);
_imapSw.Flush();
return Response();
}
It looks like you are using code from here, or similar:
http://www.codeproject.com/Articles/29594/How-to-Access-Emails-Using-the-IMAP-Protocol
That code as written is wrong and won't work for larger messages. The Response() call needs to loop over calls to .Read(), appending the results until the method returns 0 (which indicates there is no more data available.) Look at the documentation for NetworkStream.Read.
Also, you'd be much better off using an IMAP library (see Accessing Imap in C#).
You Just Have To Change Your Receive Buffer Size
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.