Jruby JavaMail undefined method getUID - jruby

I am trying to use POP3 JavaMail package to fetch email messages. Based on the JavaMail documentation both IMAPFolder and POP3Folder have getUID() methods. However the code works fine with IMAP but not with POP3. With POP3 I get the following error: undefined method ``getUID' for #<Java::ComSunMailPop3::POP3Message:0x66d7cba7>.
Below is the code:
server_messages = mbox.selectedfolder.getMessages()
msgs_to_be_fetched = Array.new
fetchprofile = javax.mail.FetchProfile.new()
fetchprofile.add(javax.mail.UIDFolder::FetchProfileItem::UID)
fetchprofile.add(javax.mail.FetchProfile::Item::FLAGS)
mbox.selectedfolder.fetch(server_messages, fetchprofile)
server_messages.each { |server_msg|
next if server_msg.getFlags().contains(javax.mail.Flags::Flag::DELETED)
uid = server_msg.getUID()
msgs_to_be_fetched << server_msg unless msg_exists(uid)
} unless server_messages.nil?

I've solved the issue. With IMAP I can just call message.getUID() but with POP3 I have to use the folder. Code below:
def getMessageUID(serverType,folder,msg)
return (serverType == 'imap'? msg.getUID() : folder.getUID(msg))
end

Related

Unable to reply messages in yahoo using JAVA MAIL API

Same piece of code works successfully in Gmail for replying messages, but in yahoo, I'm getting error.
Here is the code I've tried
Message[] messages2 = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
Message msg = messages2[i];
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
Message replyMessage = new MimeMessage(getMailSession);
replyMessage = (MimeMessage) msg.reply(false);
replyMessage.setFrom(new InternetAddress(to));
replyMessage.setText("Thanks");
replyMessage.setReplyTo(msg.getReplyTo());
// Send the message by authenticating the SMTP server
// Create a Transport instance and call the sendMessage
Transport t = session.getTransport("smtp");
try {
//connect to the smpt server using transport instance
//change the user and password accordingly
t.connect("smtp.mail.yahoo.com",table_user, table_pass);
t.sendMessage(replyMessage,
replyMessage.getAllRecipients());
} finally {
t.close();
}
System.out.println("message replied successfully ....");
The error I'm getting:
com.sun.mail.smtp.SMTPSendFailedException: 550 Request failed; Mailbox unavailable
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1634)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:889)
at mail$8.doInBackground(mail.java:1114)
at mail$8.doInBackground(mail.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Please point me to the right direction ,what I'm doing wrong.
The Yahoo mail server doesn't like one of your recipients of the reply message. Try enabling JavaMail debug output and you might get more information about what's wrong.
Note also that you're creating the replyMessage by using the MimeMessage constructor, then throwing that value away and assigning it to the return value of the reply method. You can get rid of the call to the constructor, which is doing nothing.

How to pass the credential to login to Jenkins from groovy script?

I am trying access one of the Jenkins job's log using groovy script. but getting 403 error. How do I pass the credential to login in below code?
def jsonStr1 = new URL(myEnvUrl+"warnings40Result/api/json?pretty=true").getText()
You are getting HTTP 403 which stands for Unauthorized attempt.
Possibly there is a login page of Jenkins, you should include it to access your next page. page. Have a check following link:
Groovy built-in REST/HTTP client?
def jsonStr1 = new URL(myEnvUrl+"warnings40Result/api/json?pretty=true").getText()
I tried all the solution of url:
https://stackoverflow.com/questions/25692515/groovy-built-in-rest-http-client
i think without Login Credentials code we can't access 'jsonStr1'. so i tried below code, now i am able to access but while parsing the value its giving error:
code:200
[PostBuildScript] - Problem occurred: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
my code:
def warningJsonUrl = EnvBuildUrl+"warnings40Result/api/json?token=4eca462899e426937a94006a20561011"
def authString = "admin1:admin1".getBytes().encodeBase64().toString()
def conn = warningJsonUrl.toURL().openConnection()
conn.setRequestProperty( "Authorization", "Basic ${authString}" )
if( conn.responseCode == 200 ) {
println("code:"+conn.responseCode)
def textJsonObj = new JsonSlurper().parseText(conn.content.text)
}
how i will parse as text?

How to manage QNetworkReply order from QNetworkAccessManager requests

I have a Demo Server replying JSON objects only to the client request.
I am planning to use QNetworkAccessManager as the client, this is what I did.
I defined a lambda function handling Server reply
std::function<void(QNetworkReply*)> processReplyLB = [&](QNetworkReply *reply){
static int cnt = 0;
std::cout<<"--------------------"<<(++cnt)<<"---------------------"<<std::endl;
QList<QByteArray> headerList = reply->rawHeaderList();
foreach (QByteArray header, headerList) {
std::cout<<header.constData()<<" - "<<reply->rawHeader(header).constData()<<std::endl;
}
processResult = false;
if(reply->error()){
std::cout<<"REPLY ERROR"<<std::endl;
std::cout<<reply->errorString().toUtf8().constData()<<std::endl;
} else {
QString value = reply->readAll();
std::cout<<"value = "<<value.toUtf8().constData()<<std::endl;
QJsonDocument doc = QJsonDocument::fromJson(value.toUtf8());
if(doc.isNull()){
std::cout<<"JSON document is null"<<std::endl;
}else if(doc.isEmpty()){
std::cout<<"JSON document is empty"<<std::endl;
} else if(!doc.isObject()){
std::cout<<"JSON document is not an object"<<std::endl;
} else {
QJsonObject obj = doc.object();
QString responseStr = obj.value("result").toString();
processResult = (responseStr == "ok");
if(obj.contains("message")){
QJsonValue messageValue = obj.value("message");
std::cout<<messageValue.toString().toUtf8().constData()<<std::endl;
}
}
}
reply->deleteLater();
std::cout<<"--------------------"<<(cnt)<<"---------------------"<<std::endl;
};
and I connected this lambda slot to QNetworkAccessManager in two functions used for
check if client session does exist on Server(sends a get request).
login using id and password (send a post request with parameters).
in main function, if I invoke checkSession() or login() respectively, the result is fine. but if I try to call
login();
checkSession();
in sequence, then I will get lambda invoked four times with checkSession() result came as the first, following by a null json, login json result and finally another null json.
I know QNetworkAccessManager works asynchronously, EventLoop can solve this problem, but it is not applicable in real development mode due to I am writing a client background service component.
So how can we design this client so that I can make sure login result is processed before checkSession?
BTW, I used Java Servlet for Server without asynchronous. they are just trivial doGet and doPost processes.

Bitcoind JSON-RPC : Java Jersey Client : Unexpected end of file from server Error

I am very new to bitcoin and this is my first experiment with bitcoind.
We have been trying to develop an Java based application on BTC using bitcoind (using testnet). We are using simple HTTP Post using Jersey client with basic authentication like given below. We already have jersey client as part of project dependencies. We are running on Mac OS. The bitcoind and java client are hosted in the same system.
Client client = Client.create();
String url = "http://"+username+':'+password+"#localhost:18333";
//String url = "http://localhost:18333";
System.out.println("URL is : "+url);
WebResource webResource = client.resource(url);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password.toCharArray());
}
});
String input = "{\"method\":\"getblockcount\",\"params\":[],\"id\":\"1\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
When we execute this, we are getting
Caused by: java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:772)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:769)
From the exception what I understand is, there are some server side errors but i am not able to see errors in the log files. The degug.log does not give any details.
The entries in the bitcoin.conf file is as follows:
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
Also I tried integrating with bitcoind using json-rpc client as well which resulted in the same error.
Really appreciate any help in resolving this error. Thank you in advance. Let me know if you need any further details.
Regards,
Manjunath
====== EDIT ======
When I inspect the request and response, its giving "Remote server closed the connection before sending response header" error as part of HTTP failure scenario. Following is the request data content :
URL : http://192.168.2.111:18333/
Request Data:
{
"method": "getblockcount",
"params": [],
"id": "1"
}
Please help me in understanding where the mistake is.
================ EDIT =================
Added below entries to bitcoin.conf to allow connections from client. But still facing the same error:
rpcallowip=192.168.2.111
rpcallowip=127.0.0.1
Regards,
Manjunath
After all tweaking, I am able to get it working properly. For the benefit of others, here is the Java Code for making JSON-RPC calls to bitcoind (Using Jersey Client):
bitcoin.conf entries :
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
#txindex=1
rpcallowip=192.168.2.*
rpcallowip=127.0.0.1
rpcport=8999
#rpctimeout=60000
Make sure you change the port number and dont forget to provide rpcallowip entry pointing to respective IP address.
Client Code:
DefaultClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
Boolean.TRUE);
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter(username, password));
WebResource webResource = client.resource(url);
String input = "{\"id\":\"jsonrpc\",\"method\":\"listaccounts\",\"params\":[]}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.post(ClientResponse.class, input);
Thats it. Your good to start with bitcoind integration.
Regards,
Manjunath

Having issues with node.save service between drupal and appcelerator titanium

I am writing my first app using Appcelerator Titanium and I've hit a snag that I can seem to shake. Every other service I have used is working through the JSON server (node.get, view.get,system.connect) but I cannot for the life of me get a working solution of node.save. I've tried searching for people in my same boat and can't really find anything but I also cannot find a working solution anywhere.
I used the following blog post as a starting point:
http://civicactions.com/blog/2010/may/02/tutorial_code_developing_apps_iphoneipadandroid_using_drupal_base_system
I've tried both JSON and XMLRPC but I get no response with JSON and Access Denied with XMLRPC. If I plug my JSON into the services page through drupal admin it will create a node (not a CCK node but it worked with story) but going through the app I get nothing.
The following is my output trying with XMLRPC:
Node object -
[INFO] {
sessid = b03429453c85d4bf3d600dff6511f70f;
title = "This is a new node.";
type = story;
}
[INFO] xmlrpc: begin
[INFO] xmlrpc: url: http://mysite/services/xmlrpc
[INFO] xmlrpc: method: node.save
[INFO] xmlrpc: p: story
[INFO] xmlrpc: p: This is a new node.
[INFO] xmlrpc: p: b03429453c85d4bf3d600dff6511f70f
XML being sent -
[INFO] xmlrpc: xml: <methodCall><methodName>node.save</methodName><params><param><string>story</string></param><param><string>This is a new node.</string></param><param><string>b03429453c85d4bf3d600dff6511f70f</string></param></params></methodCall>
[INFO] xmlrpc: end
Response -
[INFO] Received: <?xml version="1.0"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>401</int></value>
</member>
<member>
<name>faultString</name>
<value><string>Access denied</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
Here is what I am getting with JSON:
[INFO] {"method":"node.save","type":"story","title":"This is a new node.","sessid":"b03429453c85d4bf3d600dff6511f70f"}
[INFO] node.save response: undefined
[WARN] Exception in event callback. {
line = 90;
message = "Unable to parse JSON string";
name = SyntaxError;
sourceId = 204738256;
sourceURL = "file://localhost/Users/justin/Sites/Apps/appname/Resources/add.js";
}
I'm not getting access denied but it isn't sending a response back to the app.
Has anyone else ran into this issue and if so have you been able to find a fix for it?
There are a few problems with the modified JSON server from Sumit's blog at this moment. The patch was made to work with a previous version of services 2. Two days ago I was dealing with the same issue. I was working quite frantically and unfortunaly don't remember anymore how everything unfolded. One of the issues is that the outdated json server module makes services crash. Again, I don't remember the details anymore, but here is the solution I found. It's php 5.2 + only , as it uses json_encode and json_decode. First pull the latest stable version of JSON Server.
Main point is that json_decode should return associative arrays instead of php objects, as that is what Drupal is expecting. So you call json_decode($json_string,TRUE), using the boolean switch makes json_decode return assoc arrays. So below a quick and very dirty solution:
function json_server_server() {
$_POST = json_decode($_POST['data'],true);
$_POST = (array)$_POST;
if (!isset($_POST)) {
return drupal_to_js(array('error' => TRUE, 'data' => "JSON server accepts POST requests only."));
}
$methods = services_get_all();
services_strip_hashes($methods);
$request = $_POST['method'];
$args = array();
foreach ($methods as $method) {
if ($method['method'] == $request) {
unset($_POST['q']);
unset($_POST['method']);
$args = array();
foreach($method['args'] as $arg) {
if(isset($_POST[$arg['name']])) {
$args[] = $_POST[$arg['name']];
}
elseif($arg['optional'] == 0) {
return drupal_to_js(array("error" => TRUE, "data" => "Argument ". $arg['name'] ." not recieved"));
}
else {
$args[$arg['name']] = NULL;
}
}
$result = services_method_call($method['method'], $args);
if (is_array($result) && $result['error'] === TRUE) return drupal_to_js(array('error' => TRUE, 'data' => $result['message']));
return(json_encode($result)); //json encode the result, not including the error
}
}
return drupal_to_js(array('error' => TRUE, 'data' => "Invalid method $request"));
}
Try wrapping your parameters between quotes; like "node.save"; it worked for me.
node.get, view.get and system.connect use different permissions than node.save. Its likely that they are all authorized for the anonymous user while node.save isn't. Since you mention system.connect, I guess you already try to start an authenticated session before calling node.save. Are you sure the session is properly maintained between calls?
Also,
Exception in event callback. {
line = 90;
message = "Unable to parse JSON string";
name = SyntaxError;
sourceId = 204738256;
sourceURL = "file://localhost/Users/justin/Sites/Apps/appname/Resources/add.js";
}
This looks more like an exception in the application code handling the server response than an error server-side. It is likely that this is caused by the server returning an HTTP 403 error without a JSON body on access denied.