Unable to connect hive through JDBC java - java

I am trying to connect hive through java(eclipse). Hive is working on the linux server, where I have installed it.
I have imported all the jar files.
I am using this code
BasicConfigurator.configure();
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
final String keyPath = "Here is the keypath";
final String user = "myuser/FQDN#REALM.COM";
Configuration conf = new Configuration();
conf.set("hadoop.security.authentication", "kerberos");
System.setProperty("java.security.krb5.conf", "PATH:/krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
UserGroupInformation ugi;
UserGroupInformation.setConfiguration(conf);
ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user, keyPath);
UserGroupInformation.setLoginUser(ugi);
System.out.println("TRYING TO CONNECT");
Connection cnct = null;
cnct = DriverManager.getConnection(
"jdbc:hive2://FQDN:10000/default;principal=ADDED PRINCIPAL HERE",
"user", "pass");
System.out.println("Connected");
cnct.close();
}
The error I am getting is:
Exception in thread "main" java.sql.SQLException: Could not open connection to jdbc:hive2://FQDN:10000/default;principal=PRINCIPAL HERE: Peer indicated failure: GSS initiate failed
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:146)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:123)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at TestHiveJdbc.main(TestHiveJdbc.java:56)
Caused by: org.apache.thrift.transport.TTransportException: Peer indicated failure: GSS initiate failed
at org.apache.thrift.transport.TSaslTransport.receiveSaslMessage(TSaslTransport.java:190)
at org.apache.thrift.transport.TSaslTransport.open(TSaslTransport.java:258)
at org.apache.thrift.transport.TSaslClientTransport.open(TSaslClientTransport.java:37)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport$1.run(TUGIAssumingTransport.java:52)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport$1.run(TUGIAssumingTransport.java:49)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/javax.security.auth.Subject.doAs(Subject.java:423)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport.open(TUGIAssumingTransport.java:49)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:144)
... 5 more
Kindly help me with this.

Related

SmbException failed to connect hostname/IP_address throwing with proper credentials in Java

I need to connect to a shared folder with proper user credentials (username, password, domain).
Then when I have access to the folder, I need to list the subfolders and files in it.
Im trying with the jcifs.smb.SmbFile class and jcifs.smb.NtlmPasswordAuthentication for the authentication.
My code is the following:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domainName", "userName", "password");
SmbFile smbFile = new SmbFile("smb://servername/someFolder", auth);
for (String fileName : smbFile.list()) {
System.out.println(fileName);
}
I would be able to connect to the server with these credentials, but I'm getting this error:
Exception in thread "main" jcifs.smb.SmbException: Failed to connect: servername/IP_ADDR
jcifs.util.transport.TransportException
java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:981)
...
Anyone has any idea why am I unable to connect?
SmbFile - https://www.jcifs.org/src/docs/api/jcifs/smb/SmbFile.html
NtlmPasswordAuthentication - https://javadoc.io/static/eu.agno3.jcifs/jcifs-ng/2.1.3/jcifs/smb/NtlmPasswordAuthentication.html
I found the solution!
Because of my OS (Windows 10) I needed to use SMB2 not SMB1 (this is the default).
Solution:
Open powershell as an administrator
You need to set a property: Set -SmbServerConfiguration -EnableSMB2Protocol $true
Optional: I think it isn't necessarry but I turned off the SMB1 protocol wit the
Set -SmbServerConfiguration -EnableSMB1Protocol $false command.
Then you can check the properties with: Get -SmbServerConfiguration command, and be sure about that all of the properties have the right value.
Import the proper dependency to the pom.xml:
<dependency>
<groupId>eu.agno3.jcifs</groupId>
<artifactId>jcifs-ng</artifactId>
<version>2.1.6</version>
</dependency>
https://github.com/AgNO3/jcifs-ng
Finally the code:
public static void sendRequest() throws Exception {
CIFSContext base = SingletonContext.getInstance();
CIFSContext authed1 = base.withCredentials(new NtlmPasswordAuthentication(base, "domainName",
"userName", "password"));
try (SmbFile f = new SmbFile("smb:\\serverName\folder", authed1)) {
if (f.exists()) {
for (SmbFile file : f.listFiles()) {
System.out.println(file.getName());
}
}
}
}

MS Sql Login failed for user

I have java app with Hikari connection pool to MSSql databse.
It works perfect when i use my database, but when i want to connect to remote database i get error: Login failed for user. I saw some problems about this here but did not found the solution. I tried to change the port on MSSQL and etc but did not succeeded.
Error message:
Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Login failed for user 'user'. ClientConnectionId:a45173d9-e047-49a1-b8d0-e8507ad2a7b9
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:544)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:536)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:112)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:72)
at com.mypackage.DAOConnPool.<clinit>(DAOConnPool.java:33)
... 2 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'user'. ClientConnectionId:a45173d9-e047-49a1-b8d0-e8507ad2a7b9
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:256)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:108)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4290)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3157)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:82)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3121)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2478)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1687)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1528)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:866)
at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnectionInternal(SQLServerDataSource.java:968)
at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnection(SQLServerDataSource.java:78)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:356)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:199)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:444)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:515)
... 5 more
Here is my config:
mssql.connectionstring= jdbc:sqlserver://IP:1433;databaseName=object_registry;integratedSecurity=true;
mssql.jdbcdriver =com.microsoft.sqlserver.jdbc.SQLServerDataSource
mssql.user = user
mssql.pass = password
mssql.minConnectionPerPartition = 5
mssql.maxConnectionPerPartition = 10
mssql.partitionCount=1
Here is my connection:
try (Connection conn = DAOConnPool.getConnection(); Statement statement = conn.createStatement();) {
statement.executeUpdate(db_statement);
Here is DAOConnPool class:
public class DAOConnPool {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource dataSource;
static {
config.setDataSourceClassName(ConfigurationFile.getProperty("mssql.jdbcdriver"));
config.setJdbcUrl(ConfigurationFile.getProperty("mssql.connectionstring"));
config.setUsername(ConfigurationFile.getProperty("mssql.user"));
config.setPassword(ConfigurationFile.getProperty("mssql.pass"));
//config.addDataSourceProperty("cachePrepStmts", "true");
//config.addDataSourceProperty("prepStmtCacheSize", "250");
//config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
dataSource = new HikariDataSource(config);
}
}
public DAOConnPool() {
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
Try to remove :
config.setDataSourceClassName(ConfigurationFile.getProperty("mssql.jdbcdriver"));
I think you are trying to connect to the database remotely using windows authentication. In connection string this
integratedSecurity=true
define that you are connecting via windows authentication. If you want to connect via network you should give the appropriate privilege. If you are connecting server authentication, you need to remove that attribute from your connecting string.

java.net.UnknownHostException when attempting to connect to database

I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
host +
")(PORT=" +
port +
")))(CONNECT_DATA=(SERVICE_NAME=" +
service +
")))",
user,
password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}
However, I receive the following error:
java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
... 11 more
Caused by: java.net.UnknownHostException: null
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
... 16 more
The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.
Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?
EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.
The connection string is of the correct format. The problem is that the host isn't set. It's null, or perhaps the string "null". There's simply no other way to generate the error message java.net.UnknownHostException: null
In your sample code, you write String host = "HOST_NAME";. This makes it look like in your real code you are assigning a constant string to the variable host. However, I'm going to stick my neck out and say that in your real code you are not doing this. You are looking up the host name from somewhere, this lookup fails for some reason, you don't check this, and hence you pass a null value into the connection string.
Your JDBC url is wrong, according to the documentation it should be something like:
jdbc:oracle:driver_type:[username/password]#//host_name:port_number/service_name
In your case your code would be something like:
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#//" + host
+ ":" + port + "/" + service, user, password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}

How to connect wordpress database with JAVA ? (mysql)

I dont know much about the connection proccess i'm trying to connect wordpress database without creating new database with my remotedesktop IP in mysql. Normally i can connect localhost and i can connect to database that created with remote ip. In my server mydatabase host name/Ip adress is localhost, as i said i dont know the whole connection between url request,wp-config file and mysql. I think i'm sending request with url to wp-config and it is connecting to my localhost. Anyway i want to connect to my remotedesktop's localhost with JAVA but i couldn't. Let me explain with code . Hope i could explain myself.
Thanks in advance.
Here are the codes :
wp-config.php
define('DB_NAME', 'mydbname');
define('DB_USER', 'mydbuser');
define('DB_PASSWORD', 'mydbpass');
define('DB_HOST', '127.0.0.1');
My connection code :
public class Dt_page {
public static DataSource getDataSource(int server) {
String database_driver = null;
String database_adres = null;
String dbuser = null;
String dbpass = null;
ConnectionFactory connectionFactory;
switch (server) {
case 1://profile server
database_driver = "com.mysql.jdbc.Driver";
database_adres = "jdbc:mysql://MY_REMOTE_DESKTOP_IP:3306/?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true";
dbuser = "mydbuser";
dbpass = "mydbpass";
}
try {
Class.forName(database_driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Dt_page.class.getName()).log(Level.SEVERE, null, ex);
}
Properties props = new Properties();
props.put("user", dbuser);
props.put("password", dbpass);
props.put("autoReconnect", "true");
props.put("autoReconnectForPools", "true");
props.put("validationQuery", "SELECT 1 from dual;");
props.put("testWhileIdle","true");
connectionFactory = new DriverManagerConnectionFactory(database_adres, props);
GenericObjectPool connectionPool = new GenericObjectPool(null, 12, GenericObjectPool.WHEN_EXHAUSTED_GROW, 60*30, 12,true,true);
GenericKeyedObjectPoolFactory keyedObjectPoolFactory = new GenericKeyedObjectPoolFactory(null);
PoolableConnectionFactory poolableConnectionFactory =
new PoolableConnectionFactory(connectionFactory,
connectionPool,
keyedObjectPoolFactory,
"select 1",
30,
null,
false,
true);
PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
return dataSource;
And SQL
QueryRunner qr;
qr = new QueryRunner(Dt_page.getDataSource(1));
try {
List<Object[]> v = qr.query("Select meta_value from mydbname.wp_favorite", new ArrayListHandler());
System.out.println(v.size());
for (Object[] objects : v) {
for (Object object : objects) {
System.out.println(object);
}
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
Error Log:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1014)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2367)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2288)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.apache.commons.dbcp.DriverManagerConnectionFactory.createConnection(DriverManagerConnectionFactory.java:78)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1188)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
at org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:175)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:304)
at tazedizi.TazeDizi.main(TazeDizi.java:29)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:355)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2461)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2306)
... 19 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:305)
... 21 more
Two things to check:
Are you sure that your mysql server is configurated to listend on MY_REMOTE_DESKTOP_IP ?
Are you sure that your firewall (iptable...) allows connexion on MY_REMOTE_DESKTOP_IP on tpc port 3306 ?

Fail to connect to james server localhost

I'm trying to connect to James server localhost, but I'm getting an exception
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port:25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1545)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at mail.main(mail.java:78)
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1511)
... 7 more
The directory structure of my James Server is:
C:\apache-james-2.3.2
|
|
|
|------C:\apache-james-2.3.2\james-2.3.2
|
|------C:\apache-james-2.3.2\javamail-1.4.2
|
|------C:\apache-james-2.3.2\jaf-1.0.2
Here's the code, which is throwing an exception:
I've not changed anything in the config file of james-2.3.2 subdirectory, then why I'm
getting that exception?
Here's the code, which is throwing an exception:
// imports omitted
public class mail {
public static void main(String[] args) {
String to = "blue#localhost";
String from = "red#localhost";
String subject = "Hello";
String body = "What's up";
if ((from != null) && (to != null) && (subject != null) && (body != null)) {
try { // we have mail to send
Properties props = new Properties();
props.put("mail.host", "localhost");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("red", "red");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
Address[] add = { new InternetAddress(to) };
message.setRecipients(Message.RecipientType.TO, add);
message.setSubject(subject);
message.setContent(body, "text/plain");
message.setText(body);
Transport.send(message);
System.out.println(" Your message to " + to + " was successfully sent.");
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
The exception is saying that localhost is unreachable. I expect that your machine does not have its loopback network address (localhost / 127.0.0.1) correctly configured.
EDIT: I assume that you are running the client and server on the same machine. If not, you cannot use localhost / 127.0.0.1.
I always try to telnet to port 25 on the mailhost, to check if the server can be reached. Try to connect to 127.0.0.1 to check if James is accepting incoming connections. I presume you have checked the logs of James for errors?
Try using the IP address 127.0.0.1 instead of the hostname 'localhost' - maybe DNS lookup on your machine is not set up properly, so that it doesn't know what the name 'localhost' means.
Open the file C:\Windows\System32\drivers\etc\hosts, and make sure it contains a line like this:
127.0.0.1 localhost
Also, try switching off your firewall or anti-virus software.
try to start apache james as root user in linux or start as
Administrator on windows. and check the server is successfully
started or not on james-server.log file in logs folder
add the host name on your hosts file
127.0.0.1 localhost
file placed
on linux /etc/hosts
on windows C:\Windows\System32\drivers\etc\hosts
and restart your server.

Categories

Resources