Spring Social Facebook error - spring

I'm using Spring Social Facebook plugin; I have a very simple scenario: I want to display, on my web page, my user account Feeds; so far I have built a very simple JUnit test in order to list my FB wall posts but I'm facing some issues with Spring Social integration
I'm using spring 4.0.5 and spring social 1.1.0
From what I saw in the documentation, I don't need to use the spring social connect framework (maybe I'll use the ConnectionRepository in future in order to not always do a FB and/or twitter connection on every request, but now I don't need to handle several users)
So, after I created a test APP on FB and obtained the appClientID and appClientSecret, I wrote this simple XML configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:facebook="http://www.springframework.org/schema/social/facebook"
xmlns:twitter="http://www.springframework.org/schema/social/twitter"
xmlns:social="http://www.springframework.org/schema/social"
xmlns:linkedin="http://www.springframework.org/schema/social/linkedin"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/social/facebook http://www.springframework.org/schema/social/spring-social-facebook.xsd
http://www.springframework.org/schema/social/linkedin http://www.springframework.org/schema/social/spring-social-linkedin.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/social/twitter http://www.springframework.org/schema/social/spring-social-twitter.xsd
http://www.springframework.org/schema/social http://www.springframework.org/schema/social/spring-social.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:configuration.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />
<context:component-scan base-package="it.spring" />
<bean id="connectionFactoryLocator"
class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<bean
class="org.springframework.social.facebook.connect.FacebookConnectionFactory">
<constructor-arg value="${facebook.appKey}" />
<constructor-arg value="${facebook.appSecret}" />
</bean>
<bean
class="org.springframework.social.twitter.connect.TwitterConnectionFactory">
<constructor-arg value="${twitter.appKey}" />
<constructor-arg value="${twitter.appSecret}" />
</bean>
</list>
</property>
</bean>
</beans>
And I wrote this simple java class (I'm behind a proxy but i can reach FB....my network administrator granted me to reach FB):
public class SocialNetworkSvcImpl implements SocialNetworkingSvc
{
private static final Log logger = LogFactory.getLog(SocialNetworkSvcImpl.class.getName());
#Autowired
private Environment env;
#Value("${facebook.appId}")
private String facebookAppId;
#Value("${facebook.appSecret}")
private String facebookAppSecret;
#Value("${facebook.clientToken}")
private String facebookClientToken;
#Value("${facebook.appNamespace}")
private String facebookAppNamespace;
private ClientHttpRequestFactory requestFactory;
#Autowired
private ConnectionFactoryRegistry cfr;
#Override
public PagedList<Post> getPosts() throws Exception
{
try
{
FacebookConnectionFactory fcc = (FacebookConnectionFactory)cfr.getConnectionFactory("facebook");
Facebook facebook = fcc.createConnection(fcc.getOAuthOperations().authenticateClient()).getApi();
if( proxyEnabled )
{
if( requestFactory != null )
{
((FacebookTemplate)facebook).setRequestFactory(requestFactory);
}
else
{
throw new IllegalArgumentException("Impossibile settare la requestFactory; proxy abilitato ma requestFactory null");
}
}
PagedList<Post> result = facebook.feedOperations().getHomeFeed();
result.addAll(facebook.feedOperations().getFeed());
return result;
}
catch (Exception e)
{
String messagge = "Errore nel recupero feed: "+e.getMessage();
logger.fatal(messagge, e);
throw e;
}
}
#PostConstruct
public void initialize()
{
if( proxyEnabled )
{
if( !StringUtils.hasText(proxyHost) )
{
throw new IllegalArgumentException("Impossibile proseguire; valore proxyHost non ammesso: "+proxyHost);
}
if( proxyPort <= 0 )
{
throw new IllegalArgumentException("Impossibile proseguire; valore proxyPort non ammesso: "+proxyPort);
}
if( !StringUtils.hasText(basicHeaderValue) )
{
throw new IllegalArgumentException("Impossibile proseguire; valore basicHeaderValue non ammesso: "+basicHeaderValue);
}
String userName = null;
String password = null;
if( !StringUtils.hasText(proxyAuthUsername) )
{
if( logger.isInfoEnabled() )
{
logger.info("Nessun valore per proxyAuthUsername; controllo se siamo nel profilo sviluppo e se è presente come paramteri della JVM");
}
boolean svil = false;
String[] profili = env.getActiveProfiles();
for (int i = 0; i < profili.length; i++)
{
if( profili[i].equalsIgnoreCase("svil") )
{
svil = true;
break;
}
}
if( svil )
{
if(System.getProperty("usernameProxy") != null)
{
userName = System.getProperty("usernameProxy");
}
}
}
else
{
if( logger.isInfoEnabled() )
{
logger.info("Valorizzo la username del proxy dal file di properties");
}
userName = proxyAuthUsername;
}
if( !StringUtils.hasText(proxyAuthPassword) )
{
if( logger.isInfoEnabled() )
{
logger.info("Nessun valore per proxyAuthPassword; controllo se siamo nel profilo sviluppo e se è presente come paramteri della JVM");
}
boolean svil = false;
String[] profili = env.getActiveProfiles();
for (int i = 0; i < profili.length; i++)
{
if( profili[i].equalsIgnoreCase("svil") )
{
svil = true;
break;
}
}
if( svil )
{
if(System.getProperty("passwordProxy") != null)
{
password = System.getProperty("passwordProxy");
}
}
}
else
{
if( logger.isInfoEnabled() )
{
logger.info("Valorizzo la password del proxy dal file di properties");
}
password = proxyAuthPassword;
}
if( (StringUtils.hasText(userName) && !StringUtils.hasText(password)) || (!StringUtils.hasText(userName) && StringUtils.hasText(password)) )
{
throw new IllegalArgumentException("Impossibile proseguire; settata solo "+(StringUtils.hasText(userName)?" la username ":" la password ")+" per accesso al proxy");
}
try
{
requestFactory = new HttpComponentsClientHttpRequestFactory();
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
CredentialsProvider credsProvider = null;
if( (StringUtils.hasText(userName) && StringUtils.hasText(password)) )
{
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(userName, password));
}
HttpClientBuilder builder = HttpClients.custom();
if( credsProvider != null )
{
builder.setDefaultCredentialsProvider(credsProvider);
}
builder.setProxy(proxy);
CloseableHttpClient httpClient = builder.build();
((HttpComponentsClientHttpRequestFactory)requestFactory).setHttpClient(httpClient);
}
catch (Exception e)
{
String message = "Errore nell'inizializzazione del servizio di connessione a social network: "+e.getMessage();
logger.fatal(message, e);
throw new IllegalStateException(message);
}
}
else
{
if( logger.isInfoEnabled() )
{
logger.info("Proxy non abilitato; ci si collega direttamente ai social network");
}
}
}
}
But i'm having an error. This is my log:
2014-07-30 09:47:04,717 DEBUG [org.springframework.web.client.RestTemplate] Created POST request for "https://graph.facebook.com/oauth/access_token"
2014-07-30 09:47:04,718 DEBUG [org.springframework.web.client.RestTemplate] Setting request Accept header to [application/x-www-form-urlencoded, multipart/form-data]
2014-07-30 09:47:04,718 DEBUG [org.springframework.web.client.RestTemplate] Writing [{client_id=[${facebook.appKey}], client_secret=[e927afa9c6b3fb7e0e9344e38a5df46b], grant_type=[client_credentials]}] using [org.springframework.social.facebook.connect.FacebookOAuth2Template$1#f653852]
2014-07-30 09:47:04,761 DEBUG [org.apache.http.client.protocol.RequestAddCookies] CookieSpec selected: best-match
2014-07-30 09:47:04,797 DEBUG [org.apache.http.client.protocol.RequestAuthCache] Auth cache not set in the context
2014-07-30 09:47:04,800 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection request: [route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]
2014-07-30 09:47:04,862 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection leased: [id: 0][route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]
2014-07-30 09:47:04,867 DEBUG [org.apache.http.impl.execchain.MainClientExec] Opening connection {s}->https://graph.facebook.com:443
2014-07-30 09:47:04,890 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connecting to graph.facebook.com/173.252.100.27:443
2014-07-30 09:47:04,892 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connect to graph.facebook.com/173.252.100.27:443 timed out. Connection will be retried using another IP address
2014-07-30 09:47:04,893 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connecting to graph.facebook.com/2a03:2880:2110:cf07:face:b00c:0:1:443
2014-07-30 09:47:04,896 DEBUG [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Shutdown connection
2014-07-30 09:47:04,896 DEBUG [org.apache.http.impl.execchain.MainClientExec] Connection discarded
2014-07-30 09:47:04,897 DEBUG [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Close connection
2014-07-30 09:47:04,897 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection released: [id: 0][route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]
2014-07-30 09:47:04,901 INFO [org.apache.http.impl.execchain.RetryExec] I/O exception (java.net.SocketException) caught when processing request to {s}->https://graph.facebook.com:443: Network is unreachable
2014-07-30 09:47:04,902 DEBUG [org.apache.http.impl.execchain.RetryExec] Network is unreachable
java.net.SocketException: Network is unreachable
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334)
at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181)
at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129)
at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
2014-07-30 09:47:04,914 INFO [org.apache.http.impl.execchain.RetryExec] Retrying request to {s}->https://graph.facebook.com:443
...
2014-07-30 09:47:11,128 ERROR [it.spring.service.impl.SocialNetworkSvcImpl] Errore nel recupero feed: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:561)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334)
at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181)
at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129)
at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.net.SocketException: Network is unreachable
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545)
... 35 more
2014-07-30 09:47:11,130 ERROR [it.eng.comi.test.ComiSocialTests] I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:561)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334)
at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194)
at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181)
at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129)
at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.net.SocketException: Network is unreachable
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545)
... 35 more
Instead if I generate an APP Token on FB and directly use it in FacebookTemplate, all works pretty good.
How can I solve this issue? Am I wrong with anything? Any tip is really really appreciated
Thank you
Angelo

There are a couple of things wrong that I see right away. The primary problem you're having is a network problem--not a code problem or a Spring Social problem. Even if your network admin says you can see Facebook, the exception you show tells me otherwise. That's something you'll need to work out on your end.
Once you get past that, I doubt this will work anyway. You obtain your access token via authenticateClient(), which only grants you a client token. But then you try to use it for user-specific requests, such as obtaining the home feed. You must have a user token to do that operation and you can only get a user token via user authorization, aka the "OAuth Dance". Spring Social's ConnectController can help you with that.

Related

How to Mock Spring WebFlux WebClient :Error

Just a beginner in JUnit testing and I'm writing a small JUnit test coverage using Mockito for WebClient.
Getting Connection refused: no further information: localhost/127.0.0.1:8080 when(responseSpec.bodyToMono(String.class)).thenReturn(monoMock);
But as I have mocked request.retrieve, It should return me mockData.
Any suggestion on Mocking of request.retrieve.bodyToMono.block() would be helpful.
Method
public String getProfile(String auth) {
String userProfileUrl = temp;
WebClient.RequestHeadersSpec<?> request = WebClient.create().get().uri(URI.create(userProfileUrl))
.accept(MediaType.APPLICATION_JSON).header(AuthConstants.AUTHORIZATION, authorization);
return request.retrieve()
.bodyToMono(String.class).block();
}
Test Case
#Test
public void testgetUserProfile() {
//Mocking Web Client
final WebClient.Builder webClientBuilder = Mockito.mock(WebClient.Builder.class);
final WebClient webClient = Mockito.mock(WebClient.class);
final WebClient.RequestHeadersUriSpec headerUriSpecMock = Mockito.mock(WebClient.RequestHeadersUriSpec.class);
final WebClient.RequestHeadersSpec headersSpecMock= Mockito.mock(WebClient.RequestHeadersSpec.class);
final WebClient.RequestBodyUriSpec bodyUriSpecMock = Mockito.mock(WebClient.RequestBodyUriSpec.class);
final WebClient.RequestBodySpec bodySpecMock = Mockito.mock(WebClient.RequestBodySpec.class);
final WebClient.ResponseSpec responseSpec = Mockito.mock(WebClient.ResponseSpec.class);
final Mono res = Mockito.mock(Mono.class);
Mockito.when(webClientBuilder.baseUrl(anyString())).thenReturn(webClientBuilder);
Mockito.when(webClientBuilder.build()).thenReturn(webClient);
Mockito.when(webClient.get()).thenReturn(headerUriSpecMock);
Mockito.when(headerUriSpecMock.uri(anyString())).thenReturn(headersSpecMock);
Mockito.when(headersSpecMock.accept(MediaType.APPLICATION_JSON)).thenReturn(headersSpecMock);
Mockito.when(headersSpecMock.header(anyString())).thenReturn(headersSpecMock);
Mockito.when(headersSpecMock.retrieve()).thenReturn(responseSpec);
Mockito.when(responseSpec.bodyToMono(String.class)).thenReturn(monoMock);
Mockito.when(monoMock.block()).thenReturn(userDetails);
String tempuserDetails = authorizationUtil.getUserDetails(auth);
assertNotNull(tempuserDetails);
}
CALL TRACE : ERROR#
reactor.core.Exceptions$ReactiveException: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:8080
at reactor.core.Exceptions.propagate(Exceptions.java:326)
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:87)
at reactor.core.publisher.Mono.block(Mono.java:1162)
at com.schneider_electric.dces.tnc.util.AuthorizationUtil.getUserProfile(AuthorizationUtil.java:94)
at com.schneider_electric.dces.tnc.util.AuthorizationUtil.getUserDetails(AuthorizationUtil.java:74)
at com.schneider_electric.dces.tnc.util.AuthorizationUtilTest.testgetUserProfile(AuthorizationUtilTest.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:89)
... 35 more
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:8080
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: no further information

Spring RestTemplate HTTPs service call org.springframework.web.client.ResourceAccessException: I/O error on POST request

I have to test Rest service. When I am trying with postman or curl utility it is working fine. But when I execute it using Spring RestTemplate I am getting below error. Any idea what's wrong? I am using spring boot 1,5, Spring 4, SPring STS
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://uat.pci.api.testconsumer.com/digital/dpu/charges/bankverification/v1": Software caused connection abort: recv failed; nested exception is java.net.SocketException: Software caused connection abort: recv failed
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:673)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:414)
at com.testconsumer.consumer.workflow.integration.service.BankVerificationService.verifyBankDetails(BankVerificationService.java:113)
at com.testconsumer.consumer.workflow.integration.bankverification.BankVerificationTest.testBankVerification(BankVerificationTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:78)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.BufferingClientHttpRequestWrapper.executeInternal(BufferingClientHttpRequestWrapper.java:56)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:99)
at com.testconsumer.consumer.workflow.integration.config.RestResponseLogger.intercept(RestResponseLogger.java:26)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:659)
... 33 more
Code
#Bean
public SimpleClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(connectiontimeout);
clientHttpRequestFactory.setReadTimeout(readtimeout);
return clientHttpRequestFactory;
}
#Bean(name = "bankSerivcerestTemplate")
RestTemplate bankSerivcerestTemplate(SimpleClientHttpRequestFactory clientHttpRequestFactory) {
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(clientHttpRequestFactory);
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getInterceptors().add(new RestResponseLogger());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
try {
return super.hasError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
return true;
}
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
throw e;
}
}
});
return restTemplate;
}
public ResponseEntity<ObjectNode> verifyBankDetails(RestRequest request){
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//Headers
Map<String, Object> params = new HashMap<>();
//Params
HttpEntity<Object> httpEntity = new HttpEntity<Object>(params, headers);
ResponseEntity<ObjectNode> response = restTemplate.postForEntity(url, httpEntity, ObjectNode.class);
JsonNode root = objectMapper.valueToTree(response.getBody());
//Parse response
return response;
}
This generally happens when Server is waiting for the response from some other process e.g. client request has timed out at Server end.Server is complaining it's fine and the client has closed the TCP connection may be due to timeout or any RuntimeException at the client end.In your case, check if the endpoint has any issues with processing the request due to any exceptions or database issues.
You are receiving this error which means that the client is not responding :
Check your logs to verify that for the request through the rest template the request headers are correctly present and that you are not missing any parameters.

jUnit DataSource issue

I'm trying to print the database table names, but for some reason I get (below) when I try to test the method
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
I've looked it up and apparently you have to set up the connection manually in the test class, else it won't work (but again, the topic I've read this was from 2008). Is there any way I could not do that?
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool(){
try{
InitialContext cx = new InitialContext();
this.dataSource = (DataSource) cx.lookup("java:/comp/env/jdbc/tut_web");
} catch (NamingException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static synchronized ConnectionPool getInstance(){
if(pool == null){
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection(){
try{
return this.dataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void closeConnection(Connection connection){
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/tut_web" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/tut_web?autoReconnect=true"
username="root" password="password"
maxActive="100" maxIdle="30" maxWait="10000"
logAbandoned="true" removeAbandoned="true"
removeAbandonedTimeout="60" type="javax.sql.DataSource" />
</Context>
Stacktree:
Apr 20, 2018 5:40:11 PM com.vio.db.config.ConnectionPool <init>
SEVERE: null
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.vio.db.config.ConnectionPool.<init>(ConnectionPool.java:27)
at com.vio.db.config.ConnectionPool.getInstance(ConnectionPool.java:35)
at com.vio.repository.CRUDReflection.<init>(CRUDReflection.java:27)
at com.vio.service.CRUDReflectionTEST.setUp(CRUDReflectionTEST.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter.run(JUnit4TestMethodAdapter.java:107)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:535)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1182)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:1033)

How can i stop the connection from getting closed while reading data from Oracle DB using Spring Batch?

I have a Spring Batch with Spring boot Application in which I am reading data from external Oracle DB and Writing it to SQL Server in production environment. I am validating the connection before reading the data but even then getting Closed Connection issue.Is anyone aware of this issue ? Below is the Datasource config code and error logs.
#Slf4j
#Configuration
public class DataSourceReaderConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceReaderConfig.class);
#Autowired
private Environment env;
#SuppressWarnings("deprecation")
#ConfigurationProperties(prefix = "oracle.datasource")
#Bean(name="dataSourceReader")
#Primary
public DataSource dataSourceReader() {
LOGGER.info("Inside dataSourceReader Method");
DataSource datasource = new DataSource();
OracleDataSource ocpds = null;
try {
ocpds = new OracleDataSource();
} catch (SQLException e1) {
LOGGER.error("Error getting Oracle Datasource Connection = " + e1.getMessage());
}
ocpds.setURL(env.getProperty("oracle.datasource.url"));
ocpds.setUser(env.getProperty("oracle.datasource.username"));
ocpds.setPassword(env.getProperty("oracle.datasource.password"));
try {
ocpds.setImplicitCachingEnabled(true);
} catch (SQLException e2) {
LOGGER.error("Error Setting OracleDataSource ImplicitCachingEnabled = " + e2.getMessage());
}
try {
ocpds.setConnectionCachingEnabled(true);
} catch (SQLException e1) {
LOGGER.error("Error Setting OracleDataSource ConnectionCachingEnabled = " + e1.getMessage());
}
Properties cacheProps = new Properties();
cacheProps.setProperty("ValidateConnection","true");
try {
ocpds.setConnectionCacheProperties(cacheProps);
} catch (SQLException e) {
LOGGER.error("Error Setting OracleDataSource Connection Cache Properites = " + e.getMessage());
}
datasource.setDataSource(ocpds);
return datasource;
}
}
[0m[0m09:00:00,000 INFO [com.elm.salamah.scheduler.batch.configuration.CityBatchConfiguration] (pool-3130-thread-1) Job2 importCitiesJob Started at : Thu Dec 07 09:00:00 AST 2017
[0m[31m09:00:00,066 ERROR [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] (pool-3130-thread-1) Unexpected error occurred in scheduled task.: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLRecoverableException: Closed Connection
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy3242.getLastJobExecution(Unknown Source)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy3241.run(Unknown Source)
at com.elm.salamah.scheduler.batch.configuration.CityBatchConfiguration.performSecondJob(CityBatchConfiguration.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: Closed Connection
at oracle.jdbc.driver.PhysicalConnection.needLine(PhysicalConnection.java:5389)
at oracle.jdbc.driver.OracleStatement.closeOrCache(OracleStatement.java:1578)
at oracle.jdbc.driver.OracleStatement.close(OracleStatement.java:1563)
at oracle.jdbc.driver.OracleStatementWrapper.close(OracleStatementWrapper.java:94)
at oracle.jdbc.driver.PhysicalConnection.setTransactionIsolation(PhysicalConnection.java:4620)
at sun.reflect.GeneratedMethodAccessor276.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:79)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy3237.setTransactionIsolation(Unknown Source)
at org.springframework.jdbc.datasource.DataSourceUtils.prepareConnectionForTransaction(DataSourceUtils.java:193)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:256)
... 34 more

Netty AsyncRestTemplate Https URL - Connection reset by peer

I'm using `Netty4ClientHttpRequestFactory to configure asyncresttemplate,
public AsyncRestTemplate asyncRestTemplate(Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory,
#Qualifier("AsyncClientLoggingInterceptor") AsyncClientHttpRequestInterceptor clientHttpRequestInterceptor) {
AsyncRestTemplate restTemplate = new AsyncRestTemplate(netty4ClientHttpRequestFactory);
List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(clientHttpRequestInterceptor);
restTemplate.setInterceptors(Collections.unmodifiableList(interceptors));
return restTemplate;
}
#Bean(name = "netty4ClientHttpRequestFactory")
public Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory() {
Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory = new Netty4ClientHttpRequestFactory();
netty4ClientHttpRequestFactory.setConnectTimeout(CONNECT_TIMEOUT);
netty4ClientHttpRequestFactory.setReadTimeout(CONNECT_TIMEOUT);
return netty4ClientHttpRequestFactory;
}
ListenableFuture<ResponseEntity<Void>> future =
asyncRestTemplate.exchange(message.getToUrl(), HttpMethod.POST, httpEntity, Void.class);
Everything works fine with HTTP POST but with Https it throws the following exception,
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[?:1.8.0_74]
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[?:1.8.0_74]
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[?:1.8.0_74]
at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[?:1.8.0_74]
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) ~[?:1.8.0_74]
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288) ~[netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100) ~[netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372) ~[netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:624) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:559) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:476) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:438) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [netty-all-4.1.9.Final.jar:4.1.9.Final]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_74]
On of the reasons for the error message "Connection reset by peer" is, as the client is waiting for a response from the remote service and the connection was closed prematurely.
I configured the Netty4ClientHttpRequestFactory with,
netty4ClientHttpRequestFactory.setSslContext(SslContextBuilder.forClient().build());

Resources