jcifs-krb5: "Server not found in Kerberos database", then it works - java

I have to connect to a CIFS share from a Java program without mounting it, so I took KerberosAuthExample from jcifs-krb5 and slightly modified it; here is the code:
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import com.sun.security.auth.module.Krb5LoginModule;
import jcifs.Config;
import jcifs.smb.Kerb5Authenticator;
import jcifs.smb.SmbFile;
public class KerberosAuthExample {
private static String NAME = "MySamAccountName";
private static String PWD = "MyPassword";
private static String URL = "smb://servername/path/" ;
private static String KDC = "dc.mydomain";
private static String REALM = "MYREALM";
public static void main(String[] args) throws LoginException {
// Nothing changes if I remove the following properties
Config.setProperty("jcifs.smb.client.capabilities",Kerb5Authenticator.CAPABILITIES);
Config.setProperty("jcifs.smb.client.flags2",Kerb5Authenticator.FLAGS2);
Config.setProperty("jcifs.smb.client.signingPreferred", "true");
try {
Subject subject = new Subject();
doLogin(subject);
SmbFile file = new SmbFile(URL, new Kerb5Authenticator(subject));
SmbFile[] files = file.listFiles();
for( int i = 0; i < files.length; i++ )
System.out.println( "-->" + files[i].getName() );
} catch (Exception e) {
e.printStackTrace();
}
}
public static void doLogin(Subject subject) throws LoginException{
System.setProperty("java.security.krb5.kdc", KDC);
System.setProperty("java.security.krb5.realm", REALM);
// System.setProperty("sun.security.krb5.debug", "true") ;
Map<String,Object> state = new HashMap<String,Object>();
state.put("javax.security.auth.login.name", NAME);
state.put("javax.security.auth.login.password", PWD.toCharArray());
Map<String,Object> option = new HashMap<String,Object>();
// option.put("debug", "true");
option.put("tryFirstPass", "true");
option.put("useTicketCache", "false");
option.put("doNotPrompt", "false");
option.put("storePass", "false");
Krb5LoginModule login = new Krb5LoginModule();
login.initialize(subject, null, state, option);
if(login.login()){
login.commit();
}
}
}
This program runs correctly, i.e., it prints the files and directories contained in the path defined in URL, but an exception is printed from SmbFile.listFiles:
GSSException: No valid credentials provided (Mechanism level: Server not found in Kerberos database (7))
at sun.security.jgss.krb5.Krb5Context.initSecContext(Krb5Context.java:710)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:248)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:179)
at jcifs.smb.SpnegoContext.initSecContext(SpnegoContext.java:80)
at jcifs.smb.Kerb5Authenticator.setup(Kerb5Authenticator.java:196)
at jcifs.smb.Kerb5Authenticator.access$000(Kerb5Authenticator.java:30)
at jcifs.smb.Kerb5Authenticator$1.run(Kerb5Authenticator.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at jcifs.smb.Kerb5Authenticator.sessionSetup(Kerb5Authenticator.java:166)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:320)
at jcifs.smb.SmbSession.send(SmbSession.java:239)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbTree.send(SmbTree.java:74)
at jcifs.smb.SmbTransport.getDfsReferrals(SmbTransport.java:771)
at jcifs.smb.Dfs.getTrustedDomains(Dfs.java:85)
at jcifs.smb.Dfs.resolve(Dfs.java:220)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:916)
at jcifs.smb.SmbFile.connect(SmbFile.java:974)
at <mypackage>.KerberosAuthExample.main(KerberosAuthExample.java:34)
Caused by: KrbException: Server not found in Kerberos database (7)
at sun.security.krb5.KrbTgsRep.<init>(KrbTgsRep.java:70)
at sun.security.krb5.KrbTgsReq.getReply(KrbTgsReq.java:192)
at sun.security.krb5.KrbTgsReq.sendAndGetCreds(KrbTgsReq.java:203)
at sun.security.krb5.internal.CredentialsUtil.serviceCreds(CredentialsUtil.java:311)
at sun.security.krb5.internal.CredentialsUtil.acquireServiceCreds(CredentialsUtil.java:115)
at sun.security.krb5.Credentials.acquireServiceCreds(Credentials.java:449)
at sun.security.jgss.krb5.Krb5Context.initSecContext(Krb5Context.java:641)
... 19 more
Caused by: KrbException: Identifier doesn't match expected value (906)
at sun.security.krb5.internal.KDCRep.init(KDCRep.java:143)
at sun.security.krb5.internal.TGSRep.init(TGSRep.java:66)
at sun.security.krb5.internal.TGSRep.<init>(TGSRep.java:61)
at sun.security.krb5.KrbTgsRep.<init>(KrbTgsRep.java:55)
... 25 more
The exception is printed three times, then the list of files is correctly printed.
I found many pages with the error "Server not found in Kerberos database", which led me to double check DNS lookups and always use fully qualified names; anyway, in all the cases I could find the connection failed, while in my case it works, it's just very very noisy.
When I enable debugging, I get a lot of information, the most relevant appears to be the KRBError:
>>>KRBError:
sTime is Fri Oct 28 11:00:51 CEST 2016 1477645251000
suSec is 237586
error code is 7
error Message is Server not found in Kerberos database
realm is <MYREALM>
sname is cifs/<domainname>
msgType is 30
We don't have a test Active Directory domain, so I am using our production domain, and I don't have much control over it. Any idea to avoid all this noise?

Related

LDAP Connection/ Apache DS / Java

i wanted to make an easy LDAP Connection with using Apache DS and Java, wanted to learn and play a bit with authentification. However, when i start using the my jar file, i always get this error message:
Setting up LDAP connection ...
LDAPException(resultCode=91 (connect error), errorMessage='An error occurred while attempting to resolve address 'ldap://localhost:10389':
UnknownHostException(Der angegebene Host ist unbekannt (ldap://localhost:10389)), ldapSDKVersion=6.0.0, revision=524c20f3bbcc0d83fb56b9e136a2fd3a7f60437d')
My apache DS LDAP server looks like this:
enter image description here
My Java code:
package ldap.test;
import java.security.GeneralSecurityException;
import javax.net.SocketFactory;
import com.unboundid.ldap.sdk.BindRequest;
import com.unboundid.ldap.sdk.BindResult;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;
public final class App2 {
// hostname of the ldap instance
public static final String HOSTNAME = "ldap://localhost:10389";
// port of the ldap instance
public static final int PORT = 10389;
public static final void main(String[] args)
{
// lazy hack
if ( args.length != 4 ) {
System.out.println("One or more parameters are missing!");
System.out.println("java -jar App2.jar $cn $sn $employeenumber $password");
System.out.println("Example: java -jar App2.jar Max Mustermann 1 1");
System.exit(1);
}
// Use no key manager, and trust all certificates. This should not be used in non-trivial code!
SSLUtil sslUtil = new SSLUtil(null, new TrustAllTrustManager());
SocketFactory socketFactory;
LDAPConnection ldapConnection = null;
try {
// Create the socket factory that will be used to make a secure
// connection to the server.
socketFactory = sslUtil.createSSLSocketFactory();
System.out.print("Setting up LDAP connection ... ");
ldapConnection = new LDAPConnection(socketFactory, HOSTNAME, PORT);
System.out.println("done!");
}
catch ( LDAPException ldapException ) {
System.err.println(ldapException);
System.exit(ldapException.getResultCode().intValue());
}
catch ( GeneralSecurityException exception ) {
System.err.println(exception);
System.exit(1);
}
// LDAP bindrequest and actual bind for DN search
System.out.print("Search DN for user with employeeNumber: " + args[2] + " ... ");
BindRequest ldapBind = new SimpleBindRequest(args[0], args[1]);
try {
// bind with technical user and password and search for DN
ldapConnection.bind(ldapBind);
String employeeNumber = args[2];
String userPassword = args[3];
Filter ldapFilter = Filter.createANDFilter(Filter.createEqualityFilter("number", employeeNumber));
SearchRequest searchReq = new SearchRequest("ou=users,o=Beispiel", SearchScope.SUB, ldapFilter, "dn");
SearchResult searchResult;
String foundDN = "none";
try
{
searchResult = ldapConnection.search(searchReq);
System.out.println("done!");
for ( SearchResultEntry entry : searchResult.getSearchEntries() )
{
foundDN = entry.getDN();
}
}
catch ( LDAPSearchException lse )
{
System.out.println("... error!");
// The search failed for some reason
searchResult = lse.getSearchResult();
ResultCode resultCode = lse.getResultCode();
System.out.println("Resultcode: " + resultCode);
String errorMessageFromServer = lse.getDiagnosticMessage();
System.out.println("Error message from server: " + errorMessageFromServer);
}
// now check for the foundDN if the given password is correct
if ( !foundDN.equals("none") ) {
System.out.println("Found DN for user with EmployeeNumber: " + employeeNumber + " => " + foundDN);
System.out.println("Now checking if password for user is correct!");
BindRequest userBindReq = new SimpleBindRequest(foundDN, userPassword);
BindResult userBindRes = ldapConnection.bind(userBindReq);
System.out.println("Result: " + userBindRes);
}
else {
System.out.println("No DN found for user with EmployeeNumber: " + employeeNumber);
}
}
catch ( LDAPException ldapException ) {
System.err.println(ldapException);
System.exit(ldapException.getResultCode().intValue());
}
finally {
// Close ldap connection
ldapConnection.close();
}
}
}
No idea why i cant connect to the server...
-----Edit--------
When i change the HOSTNAME to localhost, i get the following error message:
Setting up LDAP connection ... LDAPException(resultCode=91 (connect error),
errorMessage='An error occurred while attempting to connect to server localhost:10389: IOException(LDAPException(resultCode=91 (connect error),
errorMessage='An error occurred while attempting to establish a connection to server localhost/127.0.0.1:10389: SSLException(Unsupported or unrecognized SSL message),
ldapSDKVersion=6.0.0, revision=524c20f3bbcc0d83fb56b9e136a2fd3a7f60437d'))')
Well the good thing is that he can find localhost, but he cant connect to the server
I faced a similar issue, and the problem was solved by calling the LDAPConnection constructor with only two arguments ("localhost",10389). Could you check if this resolves your issue too?
Ofcourse, you should also remove the "ldap//:" prefix too!

Cloudant AuthCookie may not be null

I am currently trying to add entries into Cloudant using this link:
https://github.com/cloudant/java-cloudant#installation-and-usage
Below is my code
package sample;
import java.util.List;
import com.cloudant.client.api.CloudantClient;
public class Cloudant {
public static void main (String[] args){
String password = System.getProperty("gffgasdas");
CloudantClient client = new CloudantClient("wiz.cloudant.com",password);
System.out.println("Connected to Cloudant");
System.out.println("Server Version: " + client.serverVersion());
List<String> databases = client.getAllDbs();
System.out.println("All my databases : ");
for ( String db : databases ) {
System.out.println(db);
}
}
}
I am getting this error:
Exception in thread "main" java.lang.IllegalArgumentException: AuthCookie may not be null.
at org.lightcouch.internal.CouchDbUtil.assertNotEmpty(Unknown Source)
at com.cloudant.client.api.CloudantClient.<init>(Unknown Source)
at sample.Cloudant.main(Cloudant.java:11)
I have all the necessary important imports. Any help would be appreciated thanks.
I'm not sure you're using the right constructor. It looks like you need to use the three-argument constructor CloudantClient(cloudantAccountName, username, password).
Your line:
CloudantClient client = new CloudantClient("wiz.cloudant.com",password);
Needs to be:
CloudantClient client = new CloudantClient("wiz", "wiz", password);
The two-argument version assumes you are passing a cookie rather than a password.

JClouds-Chef: IllegalAccessError on TokenType2?

I am using the JClouds-Chef API to bootstrap a Linux VM (myapp01.me.example.com) with Chef Client, and to then run the client and configure the VM with its app stack via a typicalapp role:
package com.me.myorg.chef;
import org.jclouds.Constants
import org.jclouds.ContextBuilder
import org.jclouds.chef.ChefContext
import org.jclouds.chef.ChefService
import org.jclouds.chef.config.ChefProperties
import org.jclouds.chef.domain.BootstrapConfig
import org.jclouds.chef.util.RunListBuilder
import org.jclouds.compute.domain.ExecResponse
import org.jclouds.compute.domain.OsFamily
import org.jclouds.domain.LoginCredentials
import org.jclouds.scriptbuilder.domain.Statement
import org.jclouds.ssh.SshClient
import org.jclouds.sshj.config.SshjSshClientModule
import com.google.common.base.Charsets
import com.google.common.collect.ImmutableSet
import com.google.common.io.Files
import com.google.common.net.HostAndPort
import com.google.inject.Key
import com.google.inject.TypeLiteral
public class ChefProvisioner {
public static void main(String[] args) {
ChefProvisioner.provision()
}
public static provision() {
String vmIp = "myapp01.me.example.com"; // A Linux VM living in our local vCenter
String vmSshUsername = "admin";
String vmSshPassword = "12345";
String endpoint = "https://mychefserver";
String client = "myuser";
String validator = "chef-validator";
String clientCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\myuser.pem"), Charsets.UTF_8);
String validatorCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\chef-validator.pem"), Charsets.UTF_8);
Properties props = new Properties();
props.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
props.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
ChefContext ctx = ContextBuilder.newBuilder("chef")
.endpoint(endpoint)
.credentials(client, clientCredential)
.overrides(props)
.modules(ImmutableSet.of(new SshjSshClientModule())) //
.buildView(ChefContext.class);
ChefService chef = ctx.getChefService();
List<String> runlist = new RunListBuilder().addRole("typicalapp").build();
BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runlist(runlist).build();
chef.updateBootstrapConfigForGroup("jclouds-chef", bootstrapConfig);
Statement bootstrap = chef.createBootstrapScriptForGroup("jclouds-chef");
SshClient.Factory sshFactory = ctx.unwrap().utils()
.injector().getInstance(Key.get(new TypeLiteral<SshClient.Factory>() {}));
SshClient ssh = sshFactory.create(HostAndPort.fromParts(vmIp, 22),
LoginCredentials.builder().user(vmSshUsername).password(vmSshPassword).build());
ssh.connect();
try {
String rawScript = bootstrap.render(OsFamily.UNIX);
ExecResponse result = ssh.exec(rawScript);
} finally {
ssh.disconnect();
}
}
}
When I run this I get:
Exception in thread "main" java.util.ServiceConfigurationError: org.jclouds.apis.ApiMetadata: Provider org.jclouds.openstack.swift.SwiftApiMetadata could not be instantiated: java.lang.IllegalAccessError: tried to access class com.google.common.reflect.TypeResolver from class org.jclouds.util.TypeToken2
at java.util.ServiceLoader.fail(ServiceLoader.java:224)
at java.util.ServiceLoader.access$100(ServiceLoader.java:181)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:377)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at com.google.common.collect.ImmutableCollection$Builder.addAll(ImmutableCollection.java:323)
at com.google.common.collect.ImmutableSet$Builder.addAll(ImmutableSet.java:633)
at org.jclouds.apis.Apis.all(Apis.java:72)
at org.jclouds.apis.Apis.withId(Apis.java:89)
at org.jclouds.ContextBuilder.newBuilder(ContextBuilder.java:168)
at org.jclouds.ContextBuilder$newBuilder.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at com.me.myorg.chef.ChefProvisioner.provision(ChefProvisioner.groovy:51)
at com.me.myorg.chef.ChefProvisioner$provision.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at com.me.myorg.chef.ChefProvisioner.main(ChefProvisioner.groovy:27)
Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.reflect.TypeResolver from class org.jclouds.util.TypeToken2
at org.jclouds.util.TypeToken2.where(TypeToken2.java:47)
at org.jclouds.rest.internal.BaseRestApiMetadata.contextToken(BaseRestApiMetadata.java:60)
at org.jclouds.rest.internal.BaseRestApiMetadata$Builder.<init>(BaseRestApiMetadata.java:74)
at org.jclouds.openstack.swift.SwiftApiMetadata$Builder.<init>(SwiftApiMetadata.java:85)
at org.jclouds.openstack.swift.SwiftApiMetadata$Builder.<init>(SwiftApiMetadata.java:81)
at org.jclouds.openstack.swift.SwiftApiMetadata$ConcreteBuilder.<init>(SwiftApiMetadata.java:108)
at org.jclouds.openstack.swift.SwiftApiMetadata$ConcreteBuilder.<init>(SwiftApiMetadata.java:108)
at org.jclouds.openstack.swift.SwiftApiMetadata.<init>(SwiftApiMetadata.java:60)
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 java.lang.Class.newInstance(Class.java:374)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:373)
... 16 more
Any ideas as to what is going on here?
You will need the following, in order to be able to bootstrap your VM:
The ip address of the VM. It must be reachable, have the port 22 open (as the bootstrap will be done via SSH) and have access to the Internet so it can install Ruby and Chef.
A client in the Chef Server and its corresponding private key. That client is used by jclouds to perform the operations against the Chef Server REST API.
The validator certificate. That certificate will be uploaded to the node so it can self-register in the Chef Server.
In this case, as the jclouds ComputeService is not being used, you'll have to manually instantiate an SSH client to connect to the virtual machine, but it should be pretty straightforward.
In the example you mention, the Git repo is cloned when using ChefSolo, but since you have a Chef Server the only thing you need to do is to configure the connection and the desired run list and attributes.
A minimal program to do that would require the following dependencies:
<!-- Required dependencies -->
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-sshj</artifactId>
<version>${jclouds.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jclouds.api</groupId>
<artifactId>chef</artifactId>
<version>${jclouds.version}</version>
</dependency>
And it could be something like the following:
Update: I've changed the configuration to match the provided knife.rb configuration, and also added a couple properties to avoid SSL errors, as your Chef endpoint is https.
// Configuration
String vmIp = "vm-ip";
String vmSshUsername = "root";
String vmSshPassword = "foo";
String endpoint = "https://mychefserver.example.com";
String client = "myuser";
String validator = "chef-validator";
String clientCredential = Files.toString(new File("/home/myuser/.chef/myuser.pem"), Charsets.UTF_8);
String validatorCredential = Files.toString(new File("/home/myuser/.chef/chef-validator.pem"), Charsets.UTF_8);
Properties props = new Properties();
props.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
props.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
/* *** First, create the context to connect to the Chef Server *** */
// Create the context and configure the SSH driver to use. sshj in this example
ChefContext ctx = ContextBuilder.newBuilder("chef")
.endpoint(endpoint)
.credentials(client, clientCredential)
.overrides(props)
.modules(ImmutableSet.of(new SshjSshClientModule())) //
.buildView(ChefContext.class);
CherService chef = ctx.getChefService();
/* *** Second, generate the bootstrap script *** */
// Generate the bootsrap configuration
List<String> runlist = new RunListBuilder().addRole("typicalapp").build();
BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runlist(runlist).build();
// Generate the bootstrap script to be executed in the VM (this will persist
// the configuration in a data bag under the key 'jclouds-chef' so it can be reused
// and then build the bootstrap script with the information in the configuration data bag)
chef.updateBootstrapConfigForGroup("jclouds-chef", bootstrapConfig);
Statement bootstrap = chef.createBootstrapScriptForGroup("jclouds-chef");
/* *** Finally create an SSH connection manually and run the script on the VM *** */
SshClient.Factory sshFactory = ctx.unwrap().utils()
.injector().getInstance(Key.get(new TypeLiteral<SshClient.Factory>() {}));
SshClient ssh = sshFactory.create(HostAndPort.fromParts(vmIp, 22),
LoginCredentials.builder().user(vmSshUsername).password(vmSshPassword).build());
ssh.connect();
try {
String rawScript = bootstrap.render(OsFamily.UNIX);
ExecResponse result = ssh.exec(rawScript);
} finally {
ssh.disconnect();
}

Getting javax.mail.AuthenticationFailedException in Tomcat7

The program attempts to send e-mail but throws a run time exception:AuthenticationFailedException.I have used smtp protocol for sending the mail.I have used TLS.Below is my Mailsender class named SendMail.java
package com.xxx.dashboard.mail;
import java.util.Map;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.edifixio.dashboard.configuration.ConfigurationBundle;
public class SendMail {
public static void sendMail(String toAddresses, String subject, String url, String name, String email){
Map<String, String> mapdata = ConfigurationBundle.getMapdata();
final String emailId = mapdata.get("mail_id");
final String username = mapdata.get("mail_username");
final String password = mapdata.get("mail_password");
final String smtpHost = mapdata.get("mail_smtp_host");
final String smtpPort = mapdata.get("mail_smtp_port");
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailId));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toAddresses));
message.setSubject(subject);
String text = "<b>Hello "+name+",</b><br/><br/> Thank you for registering with WARM for monitoring of your URL."
+ "<br/>In order to activate your account please <b>Click Here</b><br/><br/>"
+ "Once you have activated your WARM account you can login to the WARM Dashboard using your Username "
+ ""+email+".<br/>If you are having problems with the given link, "
+ "please reply back to the following Email address: warm.xxx#gmail.com.</br>This is a system generated mail. Please do not reply to this mail.<br/><br/>Thanks and Regards<br/>WARM Admin.";
message.setContent(text,"text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String args[]) {
sendMail("sumit.ghosh#xxx.com", "Hello", "h", "Rakesh", "rakesh#gmail.com");
System.out.println("Successfully send mail to - "+toAddresses);
}
}
When I am choosing Run as Java Application from Eclipse I am getting the following error log
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at 534 5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qk9sm15826619pac.16 - gsmtp
at com.xxx.dashboard.mail.SendMail.sendMail(SendMail.java:80)
at com.xxx.dashboard.mail.SendMail.main(SendMail.java:87)
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at 534 5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qk9sm15826619pac.16 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.edifixio.dashboard.mail.SendMail.sendMail(SendMail.java:74)
... 1 more
I have a properties file named config.properties where I have kept the username and password,and other credentials like port no.Please find below its code:
mail_id=test#gmail.com
mail_username=test#gmail.com
mail_password=testxxx
mail_smtp_host=smtp.gmail.com
mail_smtp_port=587
ldap_provider_ip=192.168.15.50
ldap_port=1666
ldap_base=ou=users,ou=warm,dc=xxx,dc=co,dc=in
ldap_dir_context=dc=edifixio,dc=co,dc=in
ldap_security_principal=cn=Directory Manager,dc=xxx,dc=co,dc=in
ldap_security_credential=testxxx
I had this issue as well, I had to go into my gmail account settings and under Security Enable "Access for less secure apps" to fix it.
I was also trying out the simple javax mail program using the google smtp server . On receiving Authentication failed messages ,I had to goto https://www.google.com/settings/security/lesssecureapps and turn on access for less secure apps
Log in to the gmail account specified in your properties file
Click on the circle on your top right corner -> manage your google account -> security -> Less secure app access . Turn it on
Go to https://accounts.google.com/DisplayUnlockCaptcha.
Click on continue and logout of the gmail.
Test your service. Now it will establish a connection to send mails
Your code sent mail without any exceptions in eclipse on Debian OS. Are you running any firewall or anti-virus software that might be interfering with the connection attempt?
Try with these properties:
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.auth.mechanisms=login
mail.smtp.quitwait=false
mail.debug = false
mail.username=test#gmail.com
mail.password=test
mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
mail.smtp.protocol=smtps

Using Dropbox Java API for uploading files to dropbox

I want to upload files using the java API for DropBox. The following code gets me the oauth_token and oauth_secret. but when ever I try to upload a file I get a exception.
Java Class
package com.dropbox.client;
import com.dropbox.client.DropboxAPI.Config;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
*
* #author Charan
*/
public class DBmain {
public DBmain() {
System.setProperty("java.net.useSystemProxies", "true");
Map configuration= new HashMap();
configuration.put("consumer_key", "XXXXXXXXXXXXXXXX");
configuration.put("consumer_secret", "XXXXXXXXXXXXXXXX");
configuration.put("request_token_url", "http://api.dropbox.com/0/oauth/request_token");
configuration.put("access_token_url", "http://api.dropbox.com/0/oauth/access_token");
configuration.put("authorization_url", "http://api.dropbox.com/0/oauth/authorize");
configuration.put("port",80);
//configuration.put("trusted_access_token_url","http://api.getdropbox.com/0/token");
configuration.put("server","api.getdropbox.com");
configuration.put("content_server","api-content.dropbox.com");
String username="myMailAddress#domain.com";
String password="myPassword";
try {
Authenticator auth = new Authenticator(configuration);
String url = auth.retrieveRequestToken("");
String access_key = auth.getTokenKey();
String access_secret = auth.getTokenSecret();
System.out.println(access_key);
System.out.println(access_secret);
DropboxAPI api = new DropboxAPI();
DropboxAPI.Config conf = api.new Config(configuration);
api.authenticateToken("XXXXXXXXXXXX", "XXXXXXXXXXX", conf);
System.out.println(api.isAuthenticated());
URL resource = this.getClass().getResource("/config/testing.json");
File f= new File(resource.toURI());
api.putFile("dropbox", "/Project", f);
//api.accountInfo(); //even this method gives me a exception
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DBmain();
}
}
Exception
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.http.protocol.BasicHttpContext: method <init>()V not found
at org.apache.http.impl.client.DefaultHttpClient.createHttpContext(DefaultHttpClient.java:205)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:532)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.dropbox.client.DropboxClient.putFile(DropboxClient.java:299)
at com.dropbox.client.DropboxAPI.putFile(DropboxAPI.java:463)
at com.dropbox.client.DBmain.<init>(DBmain.java:58)
at com.dropbox.client.DBmain.main(DBmain.java:70)
Java Result: 1
Some extra info
Edit Date:18-6-2011
I changed the httpclient-4.0-beta1.jar and httpcore-4.0-alpha6.jar to httpclient-4.0.jar and httpcore-4.0.1.jar respectively and I no longer get the above exception [ java.lang.NoSuchMethodError ]
This stackoverflow question helped me in solving this : java.lang.NoSuchMethodError: org.apache.http.protocol.BasicHttpContext: method <init>()V not found
But Now I get UnknownhostException on execution of any methods of the API
com.dropbox.client.DropboxException: java.net.UnknownHostException: api.getdropbox.com:80
at com.dropbox.client.RESTUtility.request(RESTUtility.java:250)
at dump.DropboxClient.accountInfo(DropboxClient.java:121)
at com.charan.client.DBmain.<init>(DBmain.java:57)
at com.charan.client.DBmain.main(DBmain.java:65)
Caused by: java.net.UnknownHostException: api.getdropbox.com:80
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:525)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:123)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:101)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:381)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.dropbox.client.RESTUtility.executeRequest(RESTUtility.java:172)
at com.dropbox.client.RESTUtility.request(RESTUtility.java:248)
... 3 more
You should use http-client 4.0.3 jar
Your class should NOT be in package com.dropbox.client. Try moving it to a different (i.e. com.yourname.client). It looks like you might be creating a name clash and inadvertently overriding something in the Dropbox client API.
You have specified api.getdropbox.com:80 as the host name. Try using api.getdropbox.com instead.

Categories