How to get gmail thread id using JavaMail API in android? - smtp

As per gimap documentation javamail new gimap doc, ImapMessage not casting to GmailMessage.
Doc code is:
GmailMessage gmsg = (GmailMessage)msg; System.out.println("Gmail message ID is " + gmsg.getMsgId()); String[] labels = gmsg.getLabels(); for (String s : labels) System.out.println("Gmail message label: " + s);
here msg is a object of ImapMessage.
Error is: java.lang.ClassCastException: com.sun.mail.imap.IMAPMessage cannot be cast to com.sun.mail.gimap.mailMessage
How to solve it?
My Imap connection code is:
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Folder;
String IMAP_PROTOCOL = "imap";
String IMAP_HOST = "imap.gmail.com";
String IMAP_PORT = "993";
private Store store;
private Folder folderInbox;
private Session session;
private Properties getServerProperties(String protocol, String host,
String port) {
Properties properties = new Properties();
// server setting
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
// SSL setting
properties.setProperty(
String.format("mail.%s.socketFactory.class", protocol),
"javax.net.ssl.SSLSocketFactory");
properties.setProperty(
String.format("mail.%s.socketFactory.fallback", protocol),
"false");
properties.setProperty(
String.format("mail.%s.socketFactory.port", protocol),
String.valueOf(port));
return properties;
}
//Now connect gmail with imap
Properties properties = getServerProperties(protocol, host, port);
session = Session.getDefaultInstance(properties);
store = session.getStore(protocol);
store.connect(userName, password);
// opens the inbox folder
folderInbox = store.getFolder(folderName);
folderInbox.open(Folder.READ_ONLY);
// fetches new messages from server
Message[] messages = folderInbox.getMessages();
for (Message msg: messages
) {
GmailMessage gmsg = (GmailMessage)msg;
System.out.println("Gmail message ID is " + gmsg.getMsgId());
String[] labels = gmsg.getLabels();
for (String s : labels)
System.out.println("Gmail message label: " + s);
}

Related

Response code 400 is returned when specifying a specific scope on GoogleTV

Question
When I specify a specific scope, a response code of 400 is returned and I am unable to go to the authentication screen.
【400 error scope】
https://www.googleapis.com/auth/fitness.heart_rate.read
https://www.googleapis.com/auth/fitness.blood_pressure.read
https://www.googleapis.com/auth/fitness.body_temperature.read
【200 OK scope】
https://www.googleapis.com/auth/fitness.body.read
https://www.googleapis.com/auth/fitness.activity.read
If you know why the response code is different between 200 and 400 even though it is the same FitnessApi, please let me know.
Also, the scope for profile and email is returned at 200 normally.
Notes
Google Cloud Platform Settings
We have enabled the FitnessAPI.
For authentication information, client ID and client secret are generated using "Client ID for TVs and devices with limited input functions".
The Fitness scope described above is set in the OAuth consent screen settings of the Google Cloud Platform.
Relevant source
private static final String OAUTH_CODE_URL = "https://oauth2.googleapis.com/device/code";
private static final String OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
private static final String SCOPE_FITNESS_BODY = "https://www.googleapis.com/auth/fitness.body.read";
private static final String SCOPE_FITNESS_ACTIVITY = "https://www.googleapis.com/auth/fitness.activity.read";
private static final String SCOPE_FITNESS_HEART_RATE = "https://www.googleapis.com/auth/fitness.heart_rate.read";
private static final String SCOPE_FITNESS_BLOOD_PRESSURE = "https://www.googleapis.com/auth/fitness.blood_pressure.read";
private static final String SCOPE_FITNESS_BODY_TEMPERATURE = "https://www.googleapis.com/auth/fitness.body_temperature.read";
private static final String SCOPE_EMAIL = "email";
private static final String SCOPE_PROFILE = "profile";
:
public Object[] postAccessToken() {
String postBody = "client_id=" + OAUTH_CLIENT_ID +
"&scope=" + SCOPE_EMAIL +
"%20" + SCOPE_FITNESS_BODY_TEMPERATURE +
"%20" + SCOPE_FITNESS_ACTIVITY +
"%20" + SCOPE_FITNESS_BODY +
"%20" + SCOPE_FITNESS_HEART_RATE +
"%20" + SCOPE_FITNESS_BLOOD_PRESSURE +
"%20" + SCOPE_PROFILE;
return postAPI(OAUTH_CODE_URL, postBody);
}
:
public Object[] postAPI(String sendUrl, String sendPostData) {
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
OutputStream outputStream = null;
String result = "";
String str = "";
int statusCode = 0;
try {
URL url = new URL(sendUrl);
urlConnection = (HttpURLConnection) url.openConnection();
String postData = sendPostData;
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.addRequestProperty("User-Agent", "Android");
urlConnection.addRequestProperty("Accept-Language", Locale.getDefault().toString());
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
// Get the response code
statusCode = urlConnection.getResponseCode();
OAuth 2.0 flow for TV and limited-input device applications have limited access scopes. However, these scopes are supported for other authentication flows, such as for mobile/desktop apps, and web apps.
The OAuth 2.0 flow for TV is supported only for the following scopes:
email
openid
profile

Unit Testing of Remote API calls, How it works with JSON Objects

In my web api, I have a method that call a service that return a deserialized JSON object. I can't find a way for unit testing that is working for me.
the following is the code from the controller:
[RequireHttps]
[Route("api/GetItem/{id}")]
public class GetItemController : ControllerBase
{
private static HttpClient client = new HttpClient();
private Item item = new Item();
[RequireHttps]
[Route("api/GetItem/{id}")]
public Item GetItem(string name, string password)
{
string url = "https://localhost:5001/";
string uri = url + "api/item/" + name+ "/" + password "/" ;
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync(uri).Result;
if (Res.IsSuccessStatusCode)
{
var MemResponse = Res.Content.ReadAsStringAsync().Result;
member = JsonConvert.DeserializeObject<Item>
(MemResponse);
}
return Ok(item);
}
}
The unit test I wrote suppose to check the wrong user name and password, but when running the test it just gray out and never runs
[TestMethod]
public void GetItemWithWrongPassword()
{
var username = "Hellow";
var pass = "There";
var controller = new GetItemController();
var response = controller.GetItem(username, pass);
var s = response.ToString();
Assert.AreEqual(s, "System.Web.Http.Results.NotFoundResult");
}
what I'm doing wrong?
Later on I want to test if the connection to the remote API.
Creating an instance of GetItemController and calling its methods is not a good idea, because the whole message pipeline is skipped in the process.
I see two options here:
Put the code (including the HttpClient) that is contained in GetItem into another class and call the method on an instance of that class, e.g.:
public class ItemClient
{
private static HttpClient client = new HttpClient();
public Item GetItem(string name, string password)
{
Item item = null;
string url = "https://localhost:5001/";
string uri = url + "api/item/" + name + "/" + password;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync(uri).Result;
if (Res.IsSuccessStatusCode)
{
var MemResponse = Res.Content.ReadAsStringAsync().Result;
item = JsonConvert.DeserializeObject<Item>(MemResponse);
}
return item;
}
}
Controller method:
[RequireHttps]
[Route("api/GetItem/{name}/{password}")]
public Item GetItem(string name, string password)
{
ItemClient client = new ItemClient();
var item = client.GetItem(name, password);
return Ok(item);
}
Test method:
[TestMethod]
public void GetItemWithWrongPassword()
{
var username = "Hellow";
var password = "There";
ItemClient client = new ItemClient();
var item = client.GetItem(username, password);
Assert.IsNull(item);
}
Call the controller method using a HttpClient in the test method:
[TestMethod]
public void GetItemWithWrongPassword()
{
var username = "Hellow";
var password = "There";
string url = "https://localhost/"; // Host of your Web API
string uri = url + "api/GetItemController/GetItem/" + username + "/" + password;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync(uri).Result;
var s = Res.ToString();
Assert.AreEqual(s, "System.Web.Http.Results.NotFoundResult");
}
I personally prefer option 1 due to two benefits:
Debugging the test is easier. Debugging a call by HttpClient (option 2)
usually means that you have to start a second instance of Visual
Studio and set a breakpoint there.
The code can be used in other projects that are not Web API services. The endpoints become simple wrappers around the actual business logic.

How to post messages to yammer private network

I want to post messages to yammer in different network. For this I have wrote the below code ,
it's giving the server not found exception.
rawtoken = Security.GetRawToken();
//TODO
//get list of Yammer tokens for this user
WebClient wc = new System.Net.WebClient();
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
wc.DownloadStringAsync(new Uri("https://www.yammer.com/api/v1/oauth/tokens.json?access_token=" + rawtoken));
void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
string tokens = e.Result;
MessageBox.Show(tokens);
List<Response> myDeserializedObjList = (List<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(tokens,typeof(List<Response>));
List<Response> response = myDeserializedObjList.Where(item => item.network_id == "992371").ToList();
accessToken = response[0].token;
WebClient wc = new System.Net.WebClient();
Uri uri = new Uri("https://www.yammer.com/api/v1/messages.json?access_token=" + accessToken);
student ns = new student();
// wc.Headers["Authorization"] = "Bearer " + accessToken; //use discoEN token here
String data = "group-id=" + ns.group_id + "&body=" + ns.body;
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
wc.UploadStringTaskAsync(uri, data);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
You should use the SDK for Windows Mobile rather than rolling your own code. It is available from the Yammer Developer site. Your code also passes the token on a URL parameter. This is no longer supported and you need to pass it on the authentication header.
A ServerNotFoundException highlights a connectivity problem. Perhaps you are not connected to the network, cannot route connections, or cannot resolve www.yammer.com via DNS.

Connecting SSIS WebService task to Spring WevService

I have a SSIS package in which i use a WebService task to call a Spring WS.
The authentication is done by client certificate and username & password.
I have tried to do it like this a simple HttpConnection and a WebService task - Error 504 Gateway Timeout. When i edit the HttpConnection and click on Test Connection i get an error that states:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
I have tried doing it with a script task and the same error.
I have even tried with a dummy console application and the same result.
I also have a java written app that actually does the job but i do not have access to it's code-behind. This basically proves that the problem is not from the server itself.
The java application has it's own keystore and the same certificates that i have installed on the server.
I opened a wireshark capture and i saw that when i used either of my apps the host made a DNS request for an address that i did not configure anywhere(it seems like a proxy address from the intranet), while the java app made a DNS request with the correct address.
I am stuck here, and i have no idea what the problem might be or what else i can do so that i would get a proper error.
Please advise!
Edit:
This is the code that calls the WS:
public static void CallWebService()
{
var _url = "https://<IP>/App/soap/DataService";
string action = "getData";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param1", "0");
parameters.Add("param2", "0");
parameters.Add("param3", "value");
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(action, parameters);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
Console.WriteLine(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string thumbprint = "CERTIFICATE THUMBPRINT";
byte[] thumbprintArray = new byte[thumbprint.Split(new char[]{ ' ' }).Length];
string[] stringArray = thumbprint.Split(new char[] { ' ' });
for (int i = 0; i < thumbprintArray.Length; i++)
{
thumbprintArray[i] = Convert.ToByte(stringArray[i], 16);
}
X509Store localStore = new X509Store("My");
localStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = localStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
foreach (X509Certificate cert in certCol)
{
if (cert.GetCertHashString() == thumbprint)
{
webRequest.ClientCertificates.Add(cert);
break;
}
}
webRequest.UseDefaultCredentials = false;
webRequest.Credentials = new NetworkCredential("USER", "PASSWORD");
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string action, Dictionary<string, string> parameters)
{
string formatedParameters = string.Empty;
string paramFormat = "<{0}>{1}</{0}>";
foreach (string key in parameters.Keys)
{
formatedParameters += string.Format(paramFormat, key, parameters[key]);
}
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(string.Format(#"
<soapenv:Envelope xmlns:soap=""http://custom/soap/"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
<soapenv:Header/>
<soapenv:Body>
<soap:{0}>
{1}
</soap:{0}>
</soapenv:Body>
</soapenv:Envelope>", action, formatedParameters));
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.