Error in JavaMail when running Selenium - jakarta-mail

I'm trying to extract an email running selenium and maven but I get the following error when trying to connect:
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.UnknownHostException: pop.google.com
at com.sun.mail.pop3.POP3Store.protocolConnect
But when I run the same exact code in a different project without selenium it works, any idea what's causing this?
public class EmailService {
private static String SERVER;
private static String USER;
private static String PASSWORD;
private static final String TEXT_FROM="SMS from";
/**
* Constructor to setup imap info
* #param server email server to connect
* #param usr email address of user
* #param passwd password of user
*/
public EmailService(String server, String usr, String passwd){
SERVER = server;
USER = usr;
PASSWORD = passwd;
}
public static String receive(String type, String receiver, Date d) {
Store store = null;
Folder folder= null;
SubjectTerm subject;
RecipientStringTerm recipient = new RecipientStringTerm(Message.RecipientType.TO,USER);
try{
//Get session
Properties props = new Properties();
//props.setProperty("mail.store.protocol","imaps");
props.put("mail.pop3.host", SERVER);
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
//Session session = Session.getInstance(props, null);
Session session = Session.getDefaultInstance(props);
//Get message store and connect
store = session.getStore("pop3s");
store.connect(SERVER,USER,PASSWORD);
//Get default folder
folder = store.getDefaultFolder();
if(folder == null) throw new Exception("No Default folder");
//Get Inbox
folder = folder.getFolder("INBOX");
if(folder == null) throw new Exception ("No Inbox");
//Open folder for read only
folder.open(Folder.READ_ONLY);

That's because there is no host named "pop.google.com". Maybe you meant "pop.gmail.com"?
It probably works on some machines because of the first common mistake described in this JavaMail FAQ entry.

Related

How to make a connection localhost and my database

I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful
Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

SAML request signature verification c#

I am creating a SAML Identity provider, and our service provider is using a third party tool Component Space to do their end's work. Identity provider I developed takes login credentials from a user and validates that user on our active directory federation server. If the user is valid then I create an SAMLResponse, sign it with X509Certificate and post it to AssertionConsumerServiceURL which I received from SAMLRequest. Now I need to verify that the SAMLRequest is coming from a valid service provider and has not be modified in between.
Initially the service provider was using HTTP redirect binding and sending the SAMLRequest, SigAlg and Signature in query string, I tried below code to verify the signature, but it always returns false.
public bool VerifyHashDynamic(string Signature, string request)
{
bool isVerified = false;
X509Certificate2 x509 = new X509Certificate2(Server.MapPath(".") + #"\X509Certificate\SP.cer", "password");
byte[] signature = Base64DecodeArray(Signature);
byte[] signedData = Base64DecodeArray(request);
RSACryptoServiceProvider rsaCSP = (RSACryptoServiceProvider)x509.PublicKey.Key;
SHA256Managed hash = new SHA256Managed();
byte[] hashedData;
bool dataOK = rsaCSP.VerifyData(signedData, CryptoConfig.MapNameToOID("SHA256"), signature);
hashedData = hash.ComputeHash(signedData);
isVerified = rsaCSP.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA256"), signature);
return isVerified;
}
Is there something wrong in above code, which is allowing the signature verification?
In order to make it work in another way, I asked our service provider to send AuthNRequest with embedded signature (HTTP-POST binding). For signature verification of posted AuthnRequest I tried XMLDocument verification, here is the code:
public Boolean VerifyXml()
{
string mystr = string.Empty;
mystr = "9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OnVuc3BlY2lmaWVkIiBBbGxvd0NyZWF0ZT0idHJ1ZSIgLz48L3NhbWxwOkF1dGhuUmVxdWVzdD4=";
mystr = GetXmlFromSAML(mystr, false);
mystr = mystr.TrimEnd().TrimStart();
X509Certificate2 myCert = new X509Certificate2(Server.MapPath(".") + #"\X509Certificate\SP.cer");
XmlDocument Doc = new XmlDocument();
Doc.PreserveWhitespace = false;
Doc.XmlResolver = null;
Doc.LoadXml(mystr);
// Check arguments.
if (Doc == null)
throw new ArgumentException("Doc");
// Create a new SignedXml object and pass it
// the XML document class.
SignedXml signedXml = new SignedXml(Doc);
// Find the "Signature" node and create a new
// XmlNodeList object.
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// This example only supports one signature for
// the entire XML document. Throw an exception
// if more than one signature was found.
if (nodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(myCert, false);
}
With above verification code I get exception "SignatureDescription could not be created for the signature algorithm supplied". I am not sure how I can have this signature verification working.
Is it really possible to manually verify the SAMLRequest signature with X509Certificate? Is it fine to allow the login check without signature verification of AuthnRequest?
I have been googling all these for last one month, but had no luck. Any help is much appreciated.

Hadoop Map Reduce - Read HDFS File - FileAlreadyExists error

I am new to Hadoop. I am trying to read an existing file on HDFS using the below code. The configuration seem file and the file path is correct as well. -
public static class Map extends Mapper<LongWritable, Text, Text, Text> {
private static Text f1, f2, hdfsfilepath;
private static HashMap<String, ArrayList<String>> friendsData = new HashMap<>();
public void setup(Context context) throws IOException {
Configuration conf = context.getConfiguration();
Path path = new Path("hdfs://cshadoop1" + conf.get("hdfsfilepath"));
FileSystem fs = FileSystem.get(path.toUri(), conf);
if (fs.exists(path)) {
BufferedReader br = new BufferedReader(
new InputStreamReader(fs.open(path)));
String line;
line = br.readLine();
while (line != null) {
StringTokenizer str = new StringTokenizer(line, ",");
String friend = str.nextToken();
ArrayList<String> friendDetails = new ArrayList<>();
while (str.hasMoreTokens()) {
friendDetails.add(str.nextToken());
}
friendsData.put(friend, friendDetails);
}
}
}
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
for (String k : friendsData.keySet()) {
context.write(new Text(k), new Text(friendsData.get(k).toString()));
}
}
}
I am getting the below exception when I run the code -
Exception in thread "main" org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory hdfs://cshadoop1/socNetData/userdata/userdata.txt already exists
at org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:146)
at org.apache.hadoop.mapreduce.JobSubmitter.checkSpecs(JobSubmitter.java:458)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:343)
I am just trying to read an existing file. Any ideas what I am missing here? Appreciate any help.
Exception tells you that your output directory already exists but it should not. Delete it or change its name.
Moreover the name of your output directory 'userdata.txt' looks like the name of a file. So check you are not mistaken in your input/output directories.

Javamail Auto-reply for my domain

Javamail Auto-reply
I would truly like to auto-reply to an email using Javamail.
I already use my domain email to send a confirmation code during registration.
What I need now is when an email is sent to choices#mydomain.com I can auto-reply with a canned email based on parsing out and reading the received email. It would be nice to include the username in the reply.
Thank you for your help!
This simplest approach is to write a program that monitors your mailbox and creates and sends a reply based on every message it sees. The JavaMail download bundle includes a sample program monitor.java that will get you started. The MimeMessage.reply method will be helpful. You'll have to fill in the content of the reply message yourself. Various other JavaMail sample programs will show you how to send a message once you've created it.
And don't forget to read the JavaMail FAQ.
Nice thinking John,I had the same problem in my project, in JSP and I solved it as shown below with java class as ReadingMail
package com;import java.io.*;import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
public class ReadingMail {
public static void main(String args[]) throws Exception {
try{
String host = "pop.gmail.com";
String user="username";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public String Manu()
{
String email=null;
try{
String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
String user="username#gmail.com";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// System.out.println("SentDate : " + message[i].getSentDate());
//System.out.println("From : " + message[i].getFrom()[0]);
email=message[i].getFrom()[0]==null?null:((InternetAddress) message[i].getFrom()[0]).getAddress();
System.out.println("From addrss is..........................."+email);
// System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
return email;
}
You can fetch the username from the database and provide it as message in this program.

silverlight Socket: Unhandled Error in Silverlight Application An attempt was made to access a socket in a way forbidden by its access permissions

I basically try to reproduce the Socket example from here: http://www.silverlightshow.net/items/Sockets-and-their-implementation-in-SL2-Beta-1-including-a-chat-like-example.aspx
I only made a small change in the client side, i.e.,
String safeHost = "127.0.0.1";
int port = 4509;
Then I got this permission error? Any idea why?
Unhandled Error in Silverlight Application An attempt was made to access a socket in a way forbidden by its access permissions.
I believe that the way the socket security checks work you need to use the same url string that your application uses. to make sure i am using the correct string i have always used this to construct my DNSEndPoint:
int Port = 4509;
DnsEndPoint ep = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, Port, AddressFamily.InterNetwork);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = true;
SocketAsyncEventArgs ea = new SocketAsyncEventArgs{RemoteEndPoint = ep};
//set up completed event handler et al.
sock.ConnectAsync(ea);
I have used this exact code in a similar chat application. By using the Application.Current.Host.Source.DnsSafeHost Property you ensure that you are using the same Dns Name to access the server with the socket that the browser is using for HttpRequests.
Also are you serving the access policy file on port 943, this is another requirement of the socket support in Silverlight.
EDIT
To Confirm that you are serving the policy file you can do a number of things.
install Fiddler, you can use it to debug all http traffic hitting your server, you should be able to see the request for the policy file.
serve your policy file dynamically and then set a break point in your server application to confirm that it is being served. this is what i did.
here is the code i used to serve the policy file:
public abstract class Server
{
protected Socket Listener { get; set; }
protected int Port { get; private set; }
protected int Backlog { get; private set; }
protected bool isStopped { get; set; }
protected SocketAsyncEventArgs AcceptArgs {get;set;}
public Server(int port)
{
AcceptArgs = new SocketAsyncEventArgs();
AcceptArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
isStopped = true;
Port = port;
Backlog = 100;
}
public Server(int port, int backlog)
{
isStopped = true;
Port = port;
Backlog = backlog;
}
public void Start()
{
isStopped = false;
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, Port);
Listener.ExclusiveAddressUse = true;
Listener.Bind(ep);
//Console.WriteLine("Listening on " + Port);
Listener.Listen(Backlog);
Listener.AcceptAsync(AcceptArgs);
}
void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
if (isStopped) return;
Socket client = e.AcceptSocket;
//Console.WriteLine("Accepted Connection From: " + client.RemoteEndPoint.ToString());
e.AcceptSocket = null;
Listener.AcceptAsync(AcceptArgs);
HandleClient(client);
}
public virtual void Stop()
{
if (isStopped) throw new InvalidOperationException("Server already Stopped!");
isStopped = true;
try
{
Listener.Shutdown(SocketShutdown.Both);
Listener.Close();
}
catch (Exception)
{
}
}
protected abstract void HandleClient(Socket Client);
}
public class PolicyServer : Server
{
public const String policyStr = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from>
<domain uri=""*"" />
</allow-from>
<grant-to>
<socket-resource port=""4530"" protocol=""tcp"" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
private byte[] policy = Encoding.ASCII.GetBytes(policyStr);
private static string policyRequestString = "<policy-file-request/>";
public PolicyServer(): base(943)
{
}
protected override void HandleClient(Socket socket)
{
TcpClient client = new TcpClient { Client = socket };
Stream s = client.GetStream();
byte[] buffer = new byte[policyRequestString.Length];
client.ReceiveTimeout = 5000;
s.Read(buffer, 0, buffer.Length);//read in the request string, but don't do anything with it
//you could confirm that it is equal to the policyRequestString
s.Write(policy, 0, policy.Length);
s.Flush();
socket.Shutdown(SocketShutdown.Both);
socket.Close(1);
client.Close();
}
}
Then to use it:
PolicyServer ps = new PolicyServer();
ps.Start();
//then when shutting down
ps.Stop();
I hosted this "server" in the same process that was running the rest of the Chat Server component. Set a breakpoint in HandleClient to confirm if it is receiving the request.

Resources