Netty AsyncRestTemplate Https URL - Connection reset by peer - spring

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());

Related

Unable to bind with active directory

I'm new in this domain and trying to bind with active directory using spring ldap client in java. I have already googled this and tried every given solution on internet but it didn't work for me. I'm getting following exception:
021-08-02T14:14:04,377 DEBUG [AbstractContextSource] - Got Ldap context on server [********]
2021-08-02T14:14:04,381 ERROR [UserService] - #### NamingException #### {}
org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C090A71, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v3839�]; remaining name ‘/’
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:228) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:397) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.find(LdapTemplate.java:1840) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.find(LdapTemplate.java:1861) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.findOne(LdapTemplate.java:1869) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.ldap.repository.query.AbstractLdapRepositoryQuery.execute(AbstractLdapRepositoryQuery.java:70) ~[spring-data-ldap-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryQueryMethodInvoker$$Lambda$1419/947388427.invoke(Unknown Source) ~[?:?]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:159) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.7.jar:5.3.7]
at com.sun.proxy.$Proxy79.findUserByUsername(Unknown Source) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_45]
Dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-ldap</artifactId>
<version>${data.ldap.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>${ldap.core.version}</version>
</dependency>
Following is what I've tried:
#Bean
public LdapContextSource contextSource()
{
LOGGER.atDebug().log("using given ldap server config: {}", ldapServerConfig);
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(ldapServerConfig.getUrl());
contextSource.setBase(ldapServerConfig.getBaseDn());
contextSource.setUserDn(ldapServerConfig.getUsername());
contextSource.setPassword(ldapServerConfig.getPassword());
contextSource.setAnonymousReadOnly(ldapServerConfig.isReadOnlyConnection());
//TODO: To add the support of TLS v1.0/v1.2/v1.3
if (ldapServerConfig.isTlsEnabled())
{
ExternalTlsDirContextAuthenticationStrategy dirContextAuthenticationStrategy = new ExternalTlsDirContextAuthenticationStrategy();
contextSource.setAuthenticationStrategy(dirContextAuthenticationStrategy);
}
return contextSource;
}
#Bean
public LdapTemplate ldapTemplate(ContextSource pooledContextSource, ContextSource contextSource)
{
LOGGER.atInfo().log("connection pooling enabled: {}", ldapServerConfig.isConnectionPooling());
return ldapServerConfig.isConnectionPooling() ? new LdapTemplate(pooledContextSource) : new LdapTemplate(contextSource);
}
private ResponseEntity<ILdapResponse> authenticate(String username)
{
ResponseEntity<ILdapResponse> responseEntity;
ILdapResponse ldapResponse;
try
{
User user = userRepository.findUserByUsername(username);
Furthermore I've tried to connect with the test server and it's working fine and successfully connected. Following are the test server details
ldap.server.url=ldap://ldap.forumsys.com:389/
ldap.server.baseDn=dc=example,dc=com
ldap.server.username=cn=read-only-admin,dc=example,dc=com
ldap.server.password=password
Also I've tried to connect with the ldap console and got the successful PROD environment connection.I don't know what i'm missing in client due to which i'm unable to connect. Please guide me if i'm missing anything. Thanks in advance
ldapsearch -d 3 -x -h <url> -p 389 -D <DN/username> -W -b <base dn> cn

Can't commit transaction JPA Repository Spring after using GCP PubSub

I have a Spring Boot app that sends and receives messages on a GCP PubSub queue. Basically I try to store in the DB some of the information that I get in the message. However when I try to commit this information or saveAndFlush() I get the error RollbackException: Error while committing the transaction. If I persists any other information that it's not triggered when the app receives an inbound message it works correctly. If I try saveAndFlush instead of save I get a NullPointerException.
What am I missing?
Thanks.
Error stack
Caused by: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:543)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:633)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:386)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy153.save(Unknown Source)
at com.sap.service.deployments.DeploymentService.lambda$saveLogs$16(DeploymentService.java:235)
at java.util.Optional.map(Optional.java:215)
at com.sap.service.deployments.DeploymentService.saveLogs(DeploymentService.java:233)
at com.sap.service.deployments.DeploymentService.processDeploymentExecutionResponse(DeploymentService.java:404)
at com.sap.service.deployments.DeploymentService.messageReceiver(DeploymentService.java:245)
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.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper$HandlerMethod.invoke(MessagingMethodInvokerHelper.java:1105)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.invokeHandlerMethod(MessagingMethodInvokerHelper.java:583)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:478)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:356)
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:108)
... 24 more
Caused by: javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534)
... 54 more
Caused by: java.lang.NullPointerException
at com.sap.config.AuditorAwareImpl.getCurrentAuditor(AuditorAwareImpl.java:13)
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:344)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205)
at com.sun.proxy.$Proxy164.getCurrentAuditor(Unknown Source)
at org.springframework.data.auditing.AuditingHandler.lambda$touchAuditor$6(AuditingHandler.java:193)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.auditing.AuditingHandler.touchAuditor(AuditingHandler.java:191)
at org.springframework.data.auditing.AuditingHandler.lambda$touch$0(AuditingHandler.java:165)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.auditing.AuditingHandler.touch(AuditingHandler.java:163)
at org.springframework.data.auditing.AuditingHandler.markModified(AuditingHandler.java:143)
at org.springframework.data.jpa.domain.support.AuditingEntityListener.touchForUpdate(AuditingEntityListener.java:112)
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.hibernate.jpa.event.internal.ListenerCallback.performCallback(ListenerCallback.java:35)
at org.hibernate.jpa.event.internal.CallbackRegistryImpl.callback(CallbackRegistryImpl.java:95)
at org.hibernate.jpa.event.internal.CallbackRegistryImpl.preUpdate(CallbackRegistryImpl.java:69)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.invokeInterceptor(DefaultFlushEntityEventListener.java:366)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.handleInterception(DefaultFlushEntityEventListener.java:348)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:299)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:170)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:232)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:92)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1360)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:451)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3210)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2378)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
... 55 more
AuditorAwareImpl
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
class AuditorAwareImpl implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
SamlUserDetails userDetails = (SamlUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //NullPointerExc on this line
return Optional.of(userDetails.getFullname() + " (" + userDetails.getAttribute("uid") + ")");
}
}
This is the configuration of the Inbound PubSub
#Component
public class PubSubInbound {
#Autowired
private DeploymentService deploymentService;
#Bean
public MessageChannel inputMessageChannel() {
return new PublishSubscribeChannel();
}
// Create an inbound channel adapter to listen to the subscription `sub-one` and send
// messages to the input message channel.
#Bean
public PubSubInboundChannelAdapter inboundChannelAdapter(
#Qualifier("inputMessageChannel") MessageChannel messageChannel,
PubSubTemplate pubSubTemplate) {
PubSubInboundChannelAdapter adapter =
new PubSubInboundChannelAdapter(pubSubTemplate, "cerberusSubscription");
adapter.setOutputChannel(messageChannel);
adapter.setAckMode(AckMode.MANUAL);
adapter.setPayloadType(String.class);
return adapter;
}
#Bean
#ServiceActivator(inputChannel = "pubsubInputChannel")
public MessageHandler messageReceiver() {
return message -> {
System.out.println("Message arrived! Payload: " + new String((byte[]) message.getPayload()));
BasicAcknowledgeablePubsubMessage originalMessage =
message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
originalMessage.ack();
deploymentService.persistLogs(
Long.parseLong(message.getHeaders().get("deploymentId", String.class)),
new String((byte[]) message.getPayload()));
};
}
}
DeploymentService
#Service
public class DeploymentService {
#Autowired
private DeploymentRepository deploymentRepository;
....
public Optional<Deployment> persistLogs(Long deploymentId, String logs){
Optional<Deployment> deploymentOpt = deploymentRepository.findById(deploymentId);
return deploymentOpt.map(deployment -> {
deployment.setLogs(logs);
return deploymentRepository.save(deployment); //ERROR HERE
});
}
....
DeploymentRepository
#Repository
public interface DeploymentRepository extends JpaRepository<Deployment, Long> { }
Solved.
SecurityContextHolder.getContext().getAuthentication()
was null when the message is coming from the GCP PubSub. Reworking the getCurrentAuditor did the trick.
#Override
public Optional<String> getCurrentAuditor() {
if(SecurityContextHolder.getContext().getAuthentication()!=null){
SamlUserDetails userDetails = (SamlUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.of(userDetails.getFullname() + " (" + userDetails.getAttribute("uid") + ")");
}else return Optional.empty();
}

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.

Connection Timed out issue while consuming REST API service

I have developed a microservice using Reactive WebFlux of Spring 5. In this, using webClient, I'm trying to consume another REST API service. Everything works fine when I'm using my personal home network however I always get connection timed out error whenever I try to consume this same REST service using my microservice while working in my office.
I suspect it has something to do with the firewall or proxy in my office network. I have already disabled the windows firewall in my machine but still not working. Any advise on this issue.
Following is the code snippet:
#RestController
public class MyRestController {
private final WebClient webClient;
public TweetController(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://mockapi.demo.com").build();
}
#GetMapping("/get-customers")
public Mono<String> someRestCall(String name) {
System.out.println("****************** /get-customers *******************");
return this.webClient
.get()
.uri("/catalogs")
.retrieve()
.bodyToMono(String.class);
}
Error:
ERROR 17996 --- [ctor-http-nio-3] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request
[GET http://localhost:8080/get-customers]
io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection
timed out: no further information: test.usdemo.xyz.com/92.54.41.24:443
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
~[na:1.8.0_171] at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
~[na:1.8.0_171] at
io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
~[netty-common-4.1.24.Final.jar:4.1.24.Final] at
java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_171] Caused by:
java.net.ConnectException: Connection timed out: no further
information ... 10 common frames omitted

Spring Social Facebook error

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.

Resources