ImapProtocol.readResponse timeout Javamail - jakarta-mail

When there is no response from the server and I still make readresponse(), It hangs there. Is there any timeout for this function?
Properties prop =new Properties();
prop.setProperty("mail.imap.port","993");
prop.setProperty("mail.imap.ssl.enable", "true");
prop.setProperty("mail.imaps.timeout", "5000");
Session session = Session.getDefaultInstance(prop);
IMAPProtocol protocol=new IMAPProtocol("username","imap.gmail.com",993,true,session.getDebugOut(), session.getProperties(),true);
protocol.login("username","password");
protocol.select("inbox");
protocol.idleStart();
protocol.readResponse();

The com.sun.mail.imap documentation has a table at the bottom that lists all of the session properties you can set for IMAP. Set the mail.imap.timeout and or mail.imaps.timeout as the timeout in milliseconds.

Related

Should a InitialDirContext object be closed explicitly everytime?

There is an application that talks to LDAP on a need basis for several operations like user info fetch, list of users, list of groups, email ids etc. Every time a request has to be made an InitialDirContext object is created and used as follows.
Properties ldapProperties = new Properties();
ldapProperties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapProperties.put(Context.PROVIDER_URL, "ldaps://serv:636");
ldapProperties.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapProperties.put(Context.SECURITY_PRINCIPAL, "user");
ldapProperties.put(Context.SECURITY_CREDENTIALS, "password");
ldapProperties.put("java.naming.ldap.attributes.binary", "tokenGroups");
InitialDirContext ctx = new InitialDirContext(ldapProperties);
ctx.search(....);
Should this "ctx" object be closed using the close() method?
If its not closed and there are multiple new InitialDirContext() creations will the old ones be automatically closed?
If it was just an internal object it will be garbage collected but what about this connection object?
No reason to close the context object each time.
You should be aware that it would be possible that the server (or some network device like a Load balancer proxy) would close the connection and then you may need to reinitialize the connection.
We have some Example JNDI solutions you may find helpful.
-jim

asynchronous script timeout

I am new to protractor & using Protractor-net. Getting an "Asynchronous script timeout: result not received in 0 seconds" exception when running Protractor-net scripts.
https://github.com/bbaia/protractor-net
Does this mean the parameter passing to identify angular element is wrong?
Found this solution to solve this -
https://github.com/angular/protractor/issues/117
How do I achieve the same in protractor-net?
You need to set async timeout to increase the timeout if you don't want it to be 0 and do it wherever the driver is instantiated.
It is particularly essential due to the nature of Angular's asynchronous behavior.
[SetUp]
public void SetUp()
{
//driver = new PhantomJSDriver();
driver = new ChromeDriver();
//SetScriptTimeout is the asysn script timeout
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5));
}
See this

GAE/Java LocalChannelFailureException at development server

I'm using Channel API (Java) with Google App Engine for my web application. I have implemented a Token-reusing-mechanism for not exceeding the Channel API Quotas that fast.
This means, that my implementation reuses an existing channel for a user that refreshes the page as long as the expiration time of the token received by the ChannelService.createChannel() call, is not over.
When refreshing my page I get the following exception (with x starting at 0 and increasing for every refresh). However, my page continues to work as intended. Is there a way to avoid the exception being thrown? Or can I just ignore the exception?
com.google.appengine.api.channel.dev.LocalChannelFailureException: Client connection with ID connection-x not found.
at com.google.appengine.api.channel.dev.Channel.getClientMessageQueue(Channel.java:79)
at com.google.appengine.api.channel.dev.ChannelManager.getNextClientMessage(ChannelManager.java:300)
at com.google.appengine.api.channel.dev.LocalChannelServlet.doGet(LocalChannelServlet.java:120)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
...
Im reusing tokens with the following classes:
When calling ChannelService.createChannel() I save the expiration date and the generated token in an Entity called "Channel"
public class Channel {
private String id;
private String token;
private Date expiration;
}
Then I have a ChannelService class that returns a valid Channel with its get() method. The channelDAO is a class that just uses a Map for storing Channels. So there is no database persistence, which would keep a token alive over a server restart.
public Channel get(String clientId) {
Calendar calendar = Calendar.getInstance();
Channel channel = channelDAO.get(clientId);
if (channel == null || calendar.getTime().after(channel.getExpiration())) {
com.google.appengine.api.channel.ChannelService channelService = ChannelServiceFactory
.getChannelService();
calendar.add(Calendar.MINUTE, CHANNEL_UPTIME);
String token = channelService.createChannel(player.toString(), CHANNEL_UPTIME);
channel = new Channel(clientId, token, calendar.getTime());
channelDAO.persist(channel);
}
return channel;
}
I fixed the problem by further investigations on the source of the exception. The Channel API works with polling requests that are executed every 500ms. I used Firefox's console to track these. Here is an example poll:
[20:40:15.978] GET http://localhost:8080/_ah/channel/dev?command=poll&channel=920a60f9b27ece1a1ba43d251fdacf2e-channel-eqt3xi-1385927324758-{clientId}&client=connection-2 [HTTP/1.1 200 OK 0ms]
In my question I stated, that the exception occurs on page reload, so the problem with this was: When the page is reloaded, something (I don't know what exactly, but i assume it has something to do with sockets getting closed and reopened on page refresh) happens which causes the client (last parameter of the GET request) to no longer be available. However, a new client is available: the client "connection-{i+1}". So when you enter the page initially, the client is "connection-0". After page refresh it is "connection-1". But as the old page used a delayed execution for the poll, a false request (still connection-0) is sent to the server, that, as a result, throws the Exception.
I fixed the problem by manually cancelling the delayed execution, when leaving the page with jQuery.
var channel = new goog.appengine.Channel('${channel.token}');
var socket = channel.open(handler);
$(window).on('beforeunload', function() {
clearTimeout(socket.pollingTimer_);
});
Your token re-use scheme should be carefully checked for bugs as that exception shouldn't occur each page reload.
There is a known issue after local server restarts but as stated it should only be only if the development server restarted.
I had the same issue using GWT and gwt-gae-channel. The solution would be something like:
Socket socket = channel.open(new SocketListener() {...});
Window.addWindowClosingHandler(new ClosingHandler() {
#Override
public void onWindowClosing(ClosingEvent event) {
socket.close();
}
});

MessagingException thrown on some machines, but on others it works fine

I'm trying to write a method that sends an email based on parameters, and it works completely on CentOS and OSX. However, the method doesn't work properly on Windows (even when recompiled on Windows) as well as some other Linux OS's - it throws a MessagingException. Does anyone have any ideas as to how I can fix this to work on Windows? Thanks!
private static void sendEmail(String towhom, String subject, String body) {
String host = "smtp.gmail.com", from = "myemail", pass = "mypassword";
Properties props = System.getProperties();
Scanner scan = new Scanner(System.in);
try {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(towhom);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(AddressException e) {
System.out.println("Invalid Email Address.");
}
catch(MessagingException e) {
System.out.print("\nInvalid Email Address, please reenter it: ");
sendEmail(scan.nextLine(), subject, body);
}
}
So yes Avast Antivirus was causing the exception to be thrown when I was trying to send the mail. If anyone else has this problem who finds this page:
Open up Avast and click on the Security tab. Then click on the AntiVirus tab on the left. Under that, click Mail Shield and go to the settings. Untick "Scan outbound mail (SMTP)" and it will work like a charm.
There is no problem with your code. It looks good.
According to the JavaMail FAQ's. Following could be the problem -
There's a firewall or anti-virus program intercepting your request.
There's something wrong in your JDK installation preventing it from finding the certificates for the trusted certificate authorities.
You're running in an application server that has overridden the JDK's list of trusted certificate authorities.
If disabling your firewall and/or anti-virus does not solve the problem then you can try and reinstall the JDK and test.

Dataservice authentication not working with serviceContext.GetReadStreamUri(..)

I have an Odata Service and a WPF client application.
Some of the Odata Service Entities have images attached to them (ie.Client).
The streaming works as long as I do not apply authentication. I can view and change the images. Once I enforce authentication everything works as expected, given the credentials check out. All but the images that is. Here are the relevant code steps / snipes.
Window Constructor code
bool iv = System.Web.Security.Membership.ValidateUser("userName", "pass");
ManageService = new InventoryContext(new Uri(...));
ManageService.SendingRequest += new EventHandler<SendingRequestEventArgs (ManageService_SendingRequest);
ManageService_SendingRequest code
//attach the authentication cookie to the request header
((HttpWebRequest)e.Request).CookieContainer = ((ClientFormsIdentity)Thread.CurrentPrincipal.Identity).AuthenticationCookies;
The call to fetch the data is async using background worker
Query Methode()
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(FetchClient);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FetchClientsCompleted);
worker.RunWorkerAsync(ClientUUID);
FetchClient
var query = from o in ManageService.Clients where o.ClientUUID.Equals((Guid)e.Argument)
...
e.Result = query;
FetchClientsCompleted
var res = e.Result as DataServiceCollection<Client>;
DataContext = res[0]; //this is all working, with and without authentication
//the next line, binding the stream to the image throws 'unauthenticated'
//it works well if authentication is disabled
imgClient.Source = new BitmapImage(ManageService.GetReadStreamUri(DataContext));
if I debug, the SendingRequest methode, usually called with any query request is NOT triggered calling GetReadStreamUri(...).
This is where I am stuck, what to do to authenticate to the service to get the stream?
Also, I took the URI generated by ManageService.GetReadStreamUri(DataContext), past it into the browser and it works, the image is displayed in the browser, if logged in.
Anyone any ideas?
The SendingRequest handler will only fire for request sent by the DataServiceContext class (your ManageService). But in the case of the picture, you only get the URL from the DataServiceContext and then let the BitmapImage actually issue the HTTP request to that URL. So the event won't fire for that request. I don't know if BitmapImage has a way for you to hook into the HTTP request pipeline (I don't think it does).
You could issue that request yourself and then use the response stream as the input for the bitmap image, in which case you get full control over the request and thus can implement authentication as appropriate.

Resources