Got a timeout error when I send an email using gmail:ClientConnector in ballerinalang - gmail-api

I try to implement a program in ballerina to send an email using ballerina gmail:ClientConnector with gmail API. But it gives a timeout error like below.
error: ballerina.lang.errors:Error, message: failed to invoke 'post' action in ClientConnector. response was not received within sender timeout of 180 seconds
at ballerina.net.http:ClientConnector.post(<native>:0)
at org.wso2.ballerina.connectors.oauth2:ClientConnector.post(org/wso2/ballerina/connectors/oauth2/ClientConnector.bal:53)
at org.wso2.ballerina.connectors.gmail:ClientConnector.sendMail(org/wso2/ballerina/connectors/gmail/gmailConnector.bal:631)
at .:main(helloworld.bal:26)
And here is the code which I implement.
import org.wso2.ballerina.connectors.gmail;
function main (string[] args) {
string clientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string userId = "webmisproject#gmail.com";
string accessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string refreshToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
gmail:ClientConnector gmailConnector = create gmail:ClientConnector(userId,accessToken,refreshToken,clientId,clientSecret);
string to = "b.wathsala.bw#gmail.com";
string subject = "Test Mail";
string from = "webmisproject#gmail.com";
string messageBody = "Hello Buddhi";
string cc = "";
string bcc = "";
string id = "";
string threadId = "";
message gmailResponse;
gmailResponse = gmail:ClientConnector.sendMail(gmailConnector,to,subject,from,messageBody,cc,bcc,id,threadId);
}
I implement this code as in main function as well as a service in ballerina, but both give same error.As well it takes little bit time to give that error.

I solved that problem. I used UBUNTU 14.04. But when I run that code in UBUNTU 16.04 the issue was solved. So I think the problem is in UBUNTU 14.04. But I don't know what is the exact issue in UBUNTU 14.04.

Related

Encode and Decode base 64 in Node JS

I have a node JS program to concat a String to an encrypted message and base-64 encoding it. in my server program when I tried to base-64 decode, i am not getting the originally generated encrypted message.
i have replicated that problem in simple program below.
In this program,
I pass an encrypted and base 64 encoded message,
decode them, concatenating another string
encode the finalMessage
decode the finalMessage
Split them to get the encrypted message
encode the encrypted message to compare with original message.
the Result is - the original message passed to this function is not the same as the final message.
function decodeAndEncode(message) {
console.log("message---"+message)
const buffer = Buffer.from(message, 'base64');
console.log("buffer---"+buffer)
const updatedStringBuffer = Buffer.from('648f3ec157637553f170bccfe56bc32058d11741d016bf120e7001148b19a4d1');
const finalEncodedMsg = Buffer.from(updatedStringBuffer+"|"+buffer).toString('base64')
console.log("updatedMessage ---"+finalEncodedMsg);
const updatedMessageBuffer = Buffer.from(finalEncodedMsg, 'base64');
console.log("updatedMessageBuffer ---"+updatedMessageBuffer);
const getBackOriginalMsg = updatedMessageBuffer.toString('utf-8',updatedStringBuffer.length+1);
console.log("getBackOriginalMsg---"+getBackOriginalMsg);
const encodedMessageBack = Buffer.from(getBackOriginalMsg).toString('base64')
console.log("encodedMessageBack--- "+encodedMessageBack)
}
const message = 'KCof0N56Z0X5piDvPO4FRL6e80oOxxPzzTMie+QRUy00RzwBn1qubNTtt8z5J+LykqlbcWSWfjGarNr4c40I+RdrI+Fi1r/wCs2ql0kvYYapTaaz9lT2EeMuwTp//kyVDUxaaHmBGaN1Ai7DQz44yKAwAnStWFP/lAuxLReQFp4A8wg9e22irkvC3bIMgpKUIheo/58WD03roH5IQsfIsY7oveODIR5s+T1lmIYBBH0IXZqwDOQpArcy82RMMCme6unhJZPIsWqSlVAEWtD89muXdnpvQRFH88exZ1v3WiYYnlJruFoGz7Yi19nrvYI9gkhoee5Idi2m1w1LmDw8EQ==';
const enc = decodeAndEncode(message)

Cannot get local IP address in ReactJS

I'm create a website using ReactJS and I want get my local IP address. I've tried few ways to do that but I was confused with result.
First, I use module on npm is local-ip-url, then use localIpUrl() to get my ip address and display with console.log(). If i use a terminal to run this .js file (eg: node index.js), it print exact result i want (192.168.x.x). But if i use browser to see console log, it shows a different result 127.0.0.0.
I've tried another ways, create my own function:
const os = require('os');
function getAvailableIp() {
let ifaces = os.networkInterfaces();
let result = {};
for (let ifname in ifaces) {
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) return;
result[ifname] = iface.address;
});
};
return result;
}
function getIp() {
let ips = getAvailableIp();
return ips.WiFi || 'localhost';
}
Same like above, when I ran code in terminal, it showed perfect result. But on browser, function os.networkInterfaces() return a empty object {}(It has a property is proto, i think it doesn't cause problem). So, it always return localhost.
Anyone can explain?

character encoding issue while reading email using java mail api

Hi I am reading emil's from a mailbox using Java mail Api.
For an email ,The from Address has Chinese characters and looks as below
(krishna 国际快 <12139#ty.com> ).
After reading the email , When I get the from Address from message using message.getFromAddress();
The from address is some thing like below
?utf-8?Q?Kris=EF=BC=88=E4=BF=9E=E7=94=9F=EF=BC=89?= <12139#ty.com>
How can I get the original from address.
The email address encoding issue while reading the email from a mail box is fixed.
StringBuffer sbFrom =null;
sbFrom = new StringBuffer();
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM: " + address.toString());
sbFrom.append(address.toString());
}
I created two solutions for this . Please find them below.
Solution 1:
Created a regular expression and checking the regular expression , If email address matches the regular expression then we decode the email address.
Please check the code below.
String ENCODED_PART_REGEX_PATTERN="=\\?([^?]+)\\?([^?]+)\\?([^?]+)\\?=";
Pattern pattern=Pattern.compile(ENCODED_PART_REGEX_PATTERN);
Matcher m =pattern.matcher(sbFrom.toString());
if(m.find()){
System.out.println("FROM: " +MimeUtility.decodeWord( sbFrom.toString()));
}else{
System.out.println("FROM: " + sbFrom.toString());
}
Solution 2: Written a method which decodes the given email address. If we get javax.mail.internet.ParseException while decoding then it means the email Address do not have any encoded characters , so we return normal string.
Please observe the below method.
public String decodeAddress(String emailId) throws UnsupportedEncodingException{
String string = "";
try{
string = MimeUtility.decodeWord(emailId);
}catch(ParseException e){
System.out.println("ParseException occured so return the same string");
string =emailId;
}
return string;
}

apache pop3 bufferedreader lines end with = (equals)

I try to receive some messages from a POP3 mail server using the apache POP3 mail client.
I use a BufferedReader to get messages from my POP3 mail server (retreiveMessage(id)). I have some mails with long lines and I read them with a loop like below. My lines are truncated into several lines ending with the equal sign (=), each line with 76 chars plus the =.
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
...
POP3Client pop = new POP3Client();
pop.setSocketFactory(SSLSocketFactory.getDefault());
pop.setDefaultTimeout(60000);
pop.connect(MAIL_SEREVR, PORT);
String username = USERNAME;
String password = PASSWORD;
isVerified = pop.login(username, password);
POP3MessageInfo[] messages = pop.listMessages();
for (POP3MessageInfo msginfo : messages) {
Date timestamp = new Date();
BufferedReader reader = (BufferedReader) pop
.retrieveMessage(msginfo.number);
if (reader == null) {
System.err.println("Could not retrieve message header.");
pop.disconnect();
System.exit(1);
}
try {
printMessageInfo(reader, msginfo.number, timestamp);
} catch (Exception e) {
e.printStackTrace();
}
pop.deleteMessage(msginfo.number);
}
pop.logout();
pop.disconnect();
So, I print the messages and since a word is too long, it is truncated like this:
this is a short line, it is OK
andThisIsALongLineWithMoreThan76CharactersButThisIsEmpiricalIJustSeeThatThe=
LineIsTruncatedAtThe76thCHAR
is this a normal behavior? can someone help me?
thanks
It doesn't sound like you're using JavaMail. It you aren't, use it, it will make life easier for you. If you are, explain in more detail what you're doing.

Database problem: how to diagnose and fix the problem?

I created an application which stores values into the database and retrieves the stored data. While running an application in run mode everything seems to work fine (the values are stored and retrieved successfully) but when I run in the debug mode the process throws IllegalStateException and so far haven't found a cause.
The method which retrieves an object Recording is the following:
public Recording getRecording(String filename) {
Recording recording = null;
String where = RECORDING_FILENAME + "='" + filename + "'";
Log.v(TAG, "retrieving recording: filename = " + filename);
try {
cursor = db.query(DATABASE_TABLE_RECORDINGS, new String[]{RECORDING_FILENAME, RECORDING_TITLE, RECORDING_TAGS, RECORDING_PRIVACY_LEVEL, RECORDING_LOCATION, RECORDING_GEO_TAGS, RECORDING_GEO_TAGGING_ENABLED, RECORDING_TIME_SECONDS, RECORDING_SELECTED_COMMUNITY}, where, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
//String filename = c.getString(0);
String title = cursor.getString(1);
String tags = cursor.getString(2);
int privacyLevel = cursor.getInt(3);
String location = cursor.getString(4);
String geoTags = cursor.getString(5);
int iGeoTaggingEnabled = cursor.getInt(6);
String recordingTime = cursor.getString(7);
String communityID = cursor.getString(8);
cursor.close();
recording = new Recording(filename, title, tags, privacyLevel, location, geoTags, iGeoTaggingEnabled, recordingTime, communityID);
}
}
catch (SQLException e) {
String msg = e.getMessage();
Log.w(TAG, msg);
recording = null;
}
return recording;
}
and it is called from another class (Settings):
private Recording getRecording(String filename) {
dbAdapter = dbAdapter.open();
Recording recording = dbAdapter.getRecording(filename);
dbAdapter.close();
return recording;
}
While running through the code above everything works fine but then I notice an exception in another thread:
alt text http://img509.imageshack.us/img509/862/illegalstateexception.jpg
and don't know neither what is the possible cause of this exception nor how to debug the code from that thread to diagnose the cause.
I would be very thankful if anyone knew what is the possible issue here.
Thank you!
Looks like that cursor.close() is inside an "if" - that's when SQLiteCursor.finalize() will throw an IllegalStateException (I googled for it). You migh be getting an empty recordset, for instance, if some other process/thread didn't have the time to commit.
Close it always, even if it's result set is empty.
I'd also advice you to access fields by names, not indices, for future compatibility. And do both close()s in finally{} blocks.

Resources