Send Spring Boot simple email - java

I'm trying to send an email using Spring Boot. However, I get the error below in the console. I try the whole thing with GMX as email provider
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.mail.MailSendException: Mail server connection failed. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate); message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)] with root cause
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol
is disabled or cipher suites are inappropriate)
Main Code:
#Autowired
private JavaMailSender javaMailSender;
private void sendMail() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo("to_1#gmail.com", "to_2#gmail.com", "to_3#yahoo.com");
msg.setSubject("Testing from Spring Boot");
msg.setText("Hello World \n Spring Boot Email");
javaMailSender.send(msg);
}
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties file:
spring.mail.protocol=smtp
spring.mail.host=mail.gmx.net
spring.mail.properties.mail.smtp.ssl.trust=mail.gmx.net
spring.mail.port=587
spring.mail.username=XYZ#gmx.de
spring.mail.password=xyz
# Other properties
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true

Related

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] after Java 13 migration

I was working on a Spring boot research project which connects to a mariadb database using Hibernate, in Java 1.8. Recently I have upgrated to Java version to 13. Now following error occures when my application try to use database connection.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.sqlDBServiceHibernateImpl' defined in file [F:\RND\negorate-inventory\negorate-data-service\target\classes\it\codegen\rnd\negorate\dataservice\services\SqlDBServiceHibernateImpl.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.codegen.rnd.negorate.dataservice.services.SqlDBServiceHibernateImpl]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.hibernateConnectorProvider' defined in file [F:\RND\negorate-inventory\negorate-data-service\target\classes\it\codegen\rnd\negorate\dataservice\connectors\HibernateConnectorProvider.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.codegen.rnd.negorate.dataservice.connectors.HibernateConnectorProvider]: Constructor threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:312)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:359)
at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:390)
at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:356)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at it.codegen.rnd.negorate.dataservice.services.SqlDBServiceHibernateImpl$$EnhancerBySpringCGLIB$$a8a80337.getSessionTokenByKey(<generated>)
Hibernate configurations in application.properties file.
hibernate.connection-url=jdbc:mariadb://192.168.2.144:3306/negorate_qa
hibernate.driver-class=org.mariadb.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MariaDB103Dialect
hibernate.hbm2ddl-auto=validate
Maven dependencies in pom.xml file.
<dependency>
<groupId>it.codegen.rnd</groupId>
<artifactId>hibernate-connector</artifactId>
<version>5.2.1.16</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.5.Final</version>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.2</version>
</dependency>
hibernate-connector is a company specific dependency which is based on hibernate-core 5.4.5.Final version.
Database specification,
mysql> status;
--------------
mysql Ver 8.0.20 for Win64 on x86_64 (MySQL Community Server - GPL)
Connection id: 1930851
Current database: negorate_qa
Current user: admin#172.16.4.60
SSL: Not in use
Using delimiter: ;
Server version: 5.5.5-10.3.9-MariaDB-1:10.3.9+maria~trusty-log mariadb.org binary distribution
Protocol version: 10
Connection: 192.168.2.144 via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: cp850
Conn. characterset: cp850
TCP port: 3306
Binary data as: Hexadecimal
Uptime: 63 days 21 hours 26 min 27 sec
I need to know what exactly happned after the Java migration and how to fix this issues.
Thank you.
( I tried severel similar questions, but none of them solved this scenario. )

Spring Boot Resource Server Invalid Token

I'm trying to configure OAuth2 for a Spring project. I used jdbc authentification and my authorization server and resource server are two separate API. My issue is now with the microservices. I'm trying to use this shared authorization server to authenticate the microservices. I can get access_token from the token endpoint.
I can check the access_token from the check_token endpoint.
My resource server configuration:
#SpringBootApplication
#EnableCircuitBreaker
#EnableDiscoveryClient
#EnableResourceServer
public class ProductApiServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApiServiceApplication.class, args);
}
}
And application.yml:
security:
oauth2:
client:
client-id: saba-product-api-service
client-secret: secret123
resource:
id: saba-product-api-service
token-info-uri: http://localhost:9999/uaa/oauth/check_token
And REST controller:
#GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
When I call the /user/me endpoint I get invalid_token.
My Resource Server log:
And my Authorization Server log:
What is wrong with my code?
Update
The problem is because of this code:
I had the same issue. In my case, I was using spring cloud oauth2, Hoxton.SR4 release and it was working. So, I change to Hoxton.SR6 and the issue was throwed. My Authoriation Server also was a Eureka's client, and the issue was origined cause this dependency. There was one dependĂȘncia inside Eureka Client, named jackson-dataformat-xml, and because it the return of check_token endpoint was converted in xml instead json. When RemoteTokenServices called check_token, and the resulta was a xml, it culdn't decerialized in map<String,Object> the right way. If you had more than one aud, scope or authorities, it picked the last one. And the active propertie was trated as string. In my case I solved the issue excluding in Authorization Server the dependency mentioned from Eureka Client, like this:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</exclusion>
</exclusions>
</dependency>
Finally, I replaced
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
with
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.5.0.RELEASE</version>
</dependency>
// gh-838
if (map.containsKey("active") && !"true".equals(String.valueOf(map.get("active")))) {
logger.debug("check_token returned active attribute: " + map.get("active"));
throw new InvalidTokenException(accessToken);
}

Jersey: "Broken pipe" instead of HTTP 401 Unauthorized

I have a POST request code that uploads a file. It uploads files correctly but fails with "Broken pipe" instead of 401 Unauthorized that I expect when I provide an incorrect API key.
I have used Postman to verify that our server sends 401 Unauthorized when a wrong API key is provided.
I am under the impression that my client code still tries to send something to the stream even though the server has already closed the connection after it had sent the 401 Unauthorized.
This is the code I am using:
try {
return target
.path("storage")
.path("upload")
.request()
.header("Authorization", apiKeyHeader)
.header("App-Type", type)
.post(Entity.entity(Files.newInputStream(file.toPath()), APPLICATION_OCTET_STREAM), String.class);
} catch (IOException e) {
e.printStackTrace(); // <-- exception comes here
}
I have also tried upgrading Jersey to the latest version available: 2.27 but that didn't change anything.
javax.ws.rs.ProcessingException: java.net.SocketException: Broken pipe (Write failed)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:496)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:357)
at org.comcom.rest.api.resource.v2.AppStorageResource.uploadFile(AppStorageResource.java:70)
This is my pom.xml config:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>2.23.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.23.1</version>
</dependency>

Can't connect to jboss server - Operation failed with status WAITING

Got this exception while trying to connect to local jboss server (wildfly-8.2.0.Final)
javax.naming.NamingException: Failed to create remoting connection [Root exception is java.lang.RuntimeException: Operation failed with status WAITING]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:36)
at org.jboss.naming.remote.client.InitialContextFactory.getInitialContext(InitialContextFactory.java:121)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:216)
at com.sample.CalculatorIntegrationTestCase.obtainProxyReferences(CalculatorIntegrationTestCase.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
Caused by: java.lang.RuntimeException: Operation failed with status WAITING
at org.jboss.naming.remote.protocol.IoFutureHelper.get(IoFutureHelper.java:89)
at org.jboss.naming.remote.client.NamingStoreCache.getRemoteNamingStore(NamingStoreCache.java:56)
at org.jboss.naming.remote.client.InitialContextFactory.getOrCreateCachedNamingStore(InitialContextFactory.java:166)
at org.jboss.naming.remote.client.InitialContextFactory.getOrCreateNamingStore(InitialContextFactory.java:139)
at org.jboss.naming.remote.client.InitialContextFactory.getInitialContext(InitialContextFactory.java:104)
... 18 more
JNDI properties are following:
#BeforeClass
public static void obtainProxyReferences() throws Throwable {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL, "remote://localhost:4447");
properties.put("jboss.naming.client.ejb.context", true);
properties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
properties.put(Context.SECURITY_PRINCIPAL, "testuser");
properties.put(Context.SECURITY_CREDENTIALS, "!Test1");
namingContext = new InitialContext(properties);
bean = (MeBeanImpl) namingContext.lookup(JNDI_NAME);
}
Telnet also says that it can't connect to server with the port 4447. I opened this port in the firewall but it didn't help.
By default WildFly uses 8080 as the remoting port. The EJB client API uses the http port, with the http-upgrade functionality, for communicating with the server for remote invocation.
Eg:
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
jndiProps.put("jboss.naming.client.ejb.context", true);
jndiProps.put(Context.SECURITY_PRINCIPAL, "testuser");
jndiProps.put(Context.SECURITY_CREDENTIALS, "!Test1");
// create a context passing these properties
Context ctx = new InitialContext(jndiProps);
// lookup
ctx.lookup(JNDI_NAME);
See: Remote EJB invocations via JNDI - EJB client API or remote-naming project
instead of using "remote://localhost:4447" use "http-remoting://localhost:8080"
properties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
When you configure jndi properties in code, lookup name should not contain ejb:
JNDI_NAME = "ear-name/ejb-name/beanClass!beanInterface.fullpath");
If you're using maven, don't forget to add this dependency:
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>8.0.0.Final</version>
<type>pom</type>
</dependency>
For JMS, you'll need these as well:
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-jms-client</artifactId>
<version>2.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-core-client</artifactId>
<version>2.2.13.Final</version>
</dependency>
This should be the only dependency you need.

getting exception in maven after creating restful client

i am using apache-tomee-jaxrs-1.5.2 server and created the restful client in java using this bellow line
Response response = WebClient.create("localhost:8080/test).path("/change/event").post(userdata);
i included following dependency in pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.0-milestone1</version>
</dependency>
now compilation is success but when i deploy using mvn tomee:deploy then i am getting the foollowing exception
localhost log file: http://www.docdroid.net/6snb/localhost-log.txt.html
catalina log file:http://www.docdroid.net/6sne/cataline-log.txt.html
i do not know which dependency has problem and here my pom.xml file
http://www.docdroid.net/6soc/mypom.txt.html
the catalina log file.
Caused by: java.lang.ExceptionInInitializerError
at org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean.setupFactory(AbstractJAXRSFactoryBean.java:320)
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:163)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.deploy(CxfRsHttpListener.java:164)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.deployPojo(CxfRsHttpListener.java:110)
at org.apache.openejb.server.rest.RESTService.deployPojo(RESTService.java:436)
at org.apache.openejb.server.rest.RESTService.afterApplicationCreated(RESTService.java:248)
at org.apache.tomee.webservices.TomeeJaxRsService.afterApplicationCreated(TomeeJaxRsService.java:51)
... 78 more
Caused by: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.impl.tl.ThreadLocalProxy is not visible from class loader
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:484)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:713)
at org.apache.cxf.jaxrs.utils.InjectionUtils.createThreadLocalProxy(InjectionUtils.java:875)
at org.apache.cxf.jaxrs.model.AbstractResourceInfo.addContextMethod(AbstractResourceInfo.java:163)
at org.apache.cxf.jaxrs.model.AbstractResourceInfo.checkContextMethod(AbstractResourceInfo.java:146)
at org.apache.cxf.jaxrs.model.AbstractResourceInfo.findContextSetterMethods(AbstractResourceInfo.java:132)
at org.apache.cxf.jaxrs.model.AbstractResourceInfo.(AbstractResourceInfo.java:65)
at org.apache.cxf.jaxrs.model.ProviderInfo.(ProviderInfo.java:29)
at org.apache.cxf.jaxrs.provider.ProviderFactory.initJaxbProviders(ProviderFactory.java:127)
at org.apache.cxf.jaxrs.provider.ProviderFactory.(ProviderFactory.java:117)
at org.apache.cxf.jaxrs.provider.ProviderFactory.getInstance(ProviderFactory.java:157)
at org.apache.cxf.jaxrs.provider.ProviderFactory.(ProviderFactory.java:71)
... 85 more
you can use provided scope as a dependency in pom.xml. then it will work.e.g
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.6.4</version>
<scope>provided</scope>
</dependency>
use scope provided.

Categories