Problem: Why is there no exception message when app crashes?
below is the code that causes the error. For reference: Usecase is only for communication with repository. While repository is only for call from the Api. No additional code is added in both usecase and repository.
private fun fetchMovies(
language: String? = null, page: Int? = null, region: String? = null, timeWindow: String
) {
viewModelScope.launch {
_homeUiState.update {
it.copy(isLoading = true)
}
val nowPlaying = async { nowPlayingUseCase(language, page, region) }
val popularMovies = async { popularMoviesUseCase(language, page, region) }
val trendingMovies = async { trendingMoviesUseCase(timeWindow) }
try {
val nowPlayingResponse = nowPlaying.await()
val popularMoviesResponse = popularMovies.await()
val trendingMoviesResponse = trendingMovies.await()
_homeUiState.update {
it.copy(
nowPlaying = apiResponseHandler(nowPlayingResponse),
popularMovies = apiResponseHandler(popularMoviesResponse),
trendingMovies = apiResponseHandler(trendingMoviesResponse)
)
}
} catch (e: Exception) {
_homeUiState.update {
it.copy(userMessage = e.localizedMessage ?: "Unexpected error occurs")
}
} finally {
_homeUiState.update {
it.copy(isLoading = false)
}
}
}
}
the cause of the crash is due to IOException (connection is set to airplane mode), and can be handled by using a supervisor scope. For some reason Android Studio's Logcat doesn't show any error messages. The only error I got is "FATAL EXCEPTION: main". Any idea why there is no error/exception details in the Logcat?
below is the screenshot of the Logcat (API Key is hidden)
---------------------------- PROCESS STARTED (17889) for package com.example.moviesapp ----------------------------
2022-10-11 11:16:22.013 17889-17914 HostConnection com.example.moviesapp D HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
2022-10-11 11:16:22.913 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> GET https://api.themoviedb.org/3/movie/now_playing?page=1&api_key=API_KEY
2022-10-11 11:16:22.913 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> END GET
2022-10-11 11:16:22.929 17889-17935 okhttp.OkHttpClient com.example.moviesapp I <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org": No address associated with hostname
2022-10-11 11:16:22.945 17889-17889 Compatibil...geReporter com.example.moviesapp D Compat change id reported: 147798919; UID 10170; state: ENABLED
2022-10-11 11:16:23.051 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> GET https://api.themoviedb.org/3/movie/popular?page=1&api_key=API_KEY
2022-10-11 11:16:23.051 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> END GET
2022-10-11 11:16:23.052 17889-17935 okhttp.OkHttpClient com.example.moviesapp I <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org": No address associated with hostname
2022-10-11 11:16:23.116 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> GET https://api.themoviedb.org/3/trending/movie/day?api_key=API_KEY
2022-10-11 11:16:23.116 17889-17935 okhttp.OkHttpClient com.example.moviesapp I --> END GET
2022-10-11 11:16:23.117 17889-17935 okhttp.OkHttpClient com.example.moviesapp I <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org": No address associated with hostname
2022-10-11 11:16:23.137 17889-17889 AndroidRuntime com.example.moviesapp E FATAL EXCEPTION: main
Process: com.example.moviesapp, PID: 17889
2022-10-11 11:16:23.157 17889-17889 Process com.example.moviesapp I Sending signal. PID: 17889 SIG: 9
---------------------------- PROCESS ENDED (17889) for package com.example.moviesapp ----------------------------
Related
I encountered a problem when connecting to a NAS shared directory using spring-integration-smb.
The problem is that I was able to connect to another shared Nas directory but for the pre-prod Nas, I encountered this problem.
Also, the shared server administrator confirmed that both directories have the same configuration.
You will find below the stack encountered
07 mars 2022;14:49:50.702 [scheduling-1] WARN jcifs.smb.SmbTransportImpl - Disconnecting transport while still in use Transport12[NAS03/XXXXXXXX:445,state=5,signingEnforced=false,usage=1]: [SmbSession[credentials=XXXXXXXXXX,targetHost=nas03,targetDomain=null,uid=0,connectionState=2,usage=1]]
07 mars 2022;14:49:50.702 [scheduling-1] WARN jcifs.smb.SmbSessionImpl - Logging off session while still in use SmbSession[credentials=XXXXXXXXX,targetHost=nas03,targetDomain=null,uid=0,connectionState=3,usage=1]:[SmbTree[share=PPD,service=null,tid=4,inDfs=false,inDomainDfs=false,connectionState=0,usage=2]]
07 mars 2022;14:49:50.737 [scheduling-1] ERROR o.s.i.handler.LoggingHandler - org.springframework.messaging.MessagingException: Problem occurred while synchronizing '' to local directory; nested exception is org.springframework.messaging.MessagingException: Failure occurred while copying '/test.csv' from the remote to the local directory; nested exception is org.springframework.core.NestedIOException: Failed to read resource [/test.csv].; nested exception is jcifs.smb.SmbException: The parameter is incorrect.
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:348)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizingMessageSource.doReceive(AbstractInboundFileSynchronizingMessageSource.java:267)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizingMessageSource.doReceive(AbstractInboundFileSynchronizingMessageSource.java:69)
at org.springframework.integration.endpoint.AbstractFetchLimitingMessageSource.doReceive(AbstractFetchLimitingMessageSource.java:47)
at org.springframework.integration.endpoint.AbstractMessageSource.receive(AbstractMessageSource.java:142)
at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:212)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:444)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.pollForMessage(AbstractPollingEndpoint.java:413)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$4(AbstractPollingEndpoint.java:348)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.lambda$execute$0(ErrorHandlingTaskExecutor.java:57)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:55)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$5(AbstractPollingEndpoint.java:341)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:95)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.messaging.MessagingException: Failure occurred while copying '/BE1_2_MOUVEMENTS_Valorisation_20211231_20220218_164451.csv' from the remote to the local directory; nested exception is org.springframework.core.NestedIOException: Failed to read resource [/BE1_2_MOUVEMENTS_Valorisation_20211231_20220218_164451.csv].; nested exception is jcifs.smb.SmbException: The parameter is incorrect.
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.copyRemoteContentToLocalFile(AbstractInboundFileSynchronizer.java:551)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.copyFileToLocalDirectory(AbstractInboundFileSynchronizer.java:488)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.copyIfNotNull(AbstractInboundFileSynchronizer.java:403)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.transferFilesFromRemoteToLocal(AbstractInboundFileSynchronizer.java:386)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.lambda$synchronizeToLocalDirectory$0(AbstractInboundFileSynchronizer.java:342)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:452)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:341)
... 21 more
Caused by: org.springframework.core.NestedIOException: Failed to read resource [/BE1_2_MOUVEMENTS_Valorisation_20211231_20220218_164451.csv].; nested exception is jcifs.smb.SmbException: The parameter is incorrect.
at org.springframework.integration.smb.session.SmbSession.read(SmbSession.java:188)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.copyRemoteContentToLocalFile(AbstractInboundFileSynchronizer.java:545)
... 27 more
Caused by: jcifs.smb.SmbException: The parameter is incorrect.
at jcifs.smb.SmbTransportImpl.checkStatus2(SmbTransportImpl.java:1467)
at jcifs.smb.SmbTransportImpl.checkStatus(SmbTransportImpl.java:1578)
at jcifs.smb.SmbTransportImpl.sendrecv(SmbTransportImpl.java:1027)
at jcifs.smb.SmbTransportImpl.send(SmbTransportImpl.java:1549)
at jcifs.smb.SmbSessionImpl.send(SmbSessionImpl.java:409)
at jcifs.smb.SmbTreeImpl.send(SmbTreeImpl.java:472)
at jcifs.smb.SmbTreeConnection.send0(SmbTreeConnection.java:404)
at jcifs.smb.SmbTreeConnection.send(SmbTreeConnection.java:318)
at jcifs.smb.SmbTreeConnection.send(SmbTreeConnection.java:298)
at jcifs.smb.SmbTreeHandleImpl.send(SmbTreeHandleImpl.java:130)
at jcifs.smb.SmbTreeHandleImpl.send(SmbTreeHandleImpl.java:117)
at jcifs.smb.SmbFile.withOpen(SmbFile.java:1775)
at jcifs.smb.SmbFile.withOpen(SmbFile.java:1744)
at jcifs.smb.SmbFile.queryPath(SmbFile.java:793)
at jcifs.smb.SmbFile.exists(SmbFile.java:879)
at jcifs.smb.SmbFile.isFile(SmbFile.java:1102)
at org.springframework.integration.smb.session.SmbSession.read(SmbSession.java:182)
... 28 more
here is my code :
#Bean
public SmbSessionFactory smbSessionFactory() {
VaultResponse vaultResponse = vaultTemplate
.opsForKeyValue(vaultPath, VaultKeyValueOperationsSupport.KeyValueBackend.KV_2).get(vaultSecretsPath.toLowerCase());
SmbSessionFactory smbSession = new SmbSessionFactory();
smbSession.setHost(properties.getNasHost());
smbSession.setPort(properties.getNasPort());
smbSession.setDomain(properties.getNasDomain());
if (vaultResponse != null) {
Map<String, Object> data = vaultResponse.getData();
smbSession.setUsername(data != null && data.get("nasUsername") != null ? (String) data.get("nasUsername") : "");
smbSession.setPassword(data != null && data.get("nasPassword") != null ? (String) data.get("nasPassword") : "");
}
smbSession.setShareAndDir(properties.getNasShareAndDir());
smbSession.setReplaceFile(true);
smbSession.setSmbMinVersion(DialectVersion.SMB1);
smbSession.setSmbMaxVersion(DialectVersion.SMB311);
return smbSession;
}
thank you in advance,
Here is the sender verticle
I have set multicast enabled and set the public host to my machines ip address
VertxOptions options = new VertxOptions()
.setClusterManager(ClusterManagerConfig.getClusterManager());
EventBusOptions eventBusOptions = new EventBusOptions()
.setClustered(true)
.setClusterPublicHost("10.10.1.160");
options.setEventBusOptions(eventBusOptions);
Vertx.clusteredVertx(options, res -> {
if (res.succeeded()) {
Vertx vertx = res.result();
vertx.deployVerticle(new requestHandler());
vertx.deployVerticle(new requestSender());
EventBus eventBus = vertx.eventBus();
eventBus.send("some.address","hello",reply -> {
System.out.println(reply.toString());
});
} else {
LOGGER.info("Failed: " + res.cause());
}
});
}
here's the reciever verticle
VertxOptions options = new VertxOptions().setClusterManager(mgr);
options.setEventBusOptions(new EventBusOptions()
.setClustered(true)
.setClusterPublicHost("10.10.1.174") );
Vertx.clusteredVertx(options, res -> {
if (res.succeeded()) {
Vertx vertx1 = res.result();
System.out.println("Success");
EventBus eb = vertx1.eventBus();
System.out.println("ready");
eb.consumer("some.address", message -> {
message.reply("hello hello");
});
} else {
System.out.println("Failed");
}
});
I get this result when i run both main verticles , so the verticles are detected by hazelcast and a connection is established
INFO: [10.10.1.160]:33001 [dev] [3.10.5] Established socket connection between /10.10.1.160:33001 and /10.10.1.174:35725
Jan 11, 2021 11:45:10 AM com.hazelcast.internal.cluster.ClusterService
INFO: [10.10.1.160]:33001 [dev] [3.10.5]
Members {size:2, ver:2} [
Member [10.10.1.160]:33001 - 51b8c249-6b3c-4ca8-a238-c651845629d8 this
Member [10.10.1.174]:33001 - 1cba1680-025e-469f-bad6-884111313672
]
Jan 11, 2021 11:45:10 AM com.hazelcast.internal.partition.impl.MigrationManager
INFO: [10.10.1.160]:33001 [dev] [3.10.5] Re-partitioning cluster data... Migration queue size: 271
Jan 11, 2021 11:45:11 AM com.hazelcast.nio.tcp.TcpIpAcceptor
But when the event-bus tries to send a message to given address i encounter this error is this a problem with event-bus configuration?
Jan 11, 2021 11:59:57 AM io.vertx.core.eventbus.impl.clustered.ConnectionHolder
WARNING: Connecting to server 10.10.1.174:39561 failed
io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /10.10.1.174:39561
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:327)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:665)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
... 11 more
In Vert.x 3, the cluster host and cluster public host default to localhost.
If you only change the cluster public host in VertxOptions, Vert.x will bind EventBus transport servers to localhost while telling other nodes to connect to the public host.
This kind of configuration is needed when running Vert.x on some cloud providers, but in most cases you only need to set the cluster host (and then the public host will default to its value):
EventBusOptions eventBusOptions = new EventBusOptions()
.setClustered(true)
.setHost("10.10.1.160");
I am using hazelcast 3.8.3. Occasionally, I have Operation TimeoutException (GetOperation). I have 4 nodes in the same Hz cluster.
Application throws error
..
Caused by: java.util.concurrent.ExecutionException: com.hazelcast.core.OperationTimeoutException: GetOperation invocation failed to complete due to operation-heartbeat-timeout. Current time: 2020-04-23 19:17:37.414. Start time: 2020-04-23 19:14:16.456. Total elapsed time: 200958 ms. Last operation heartbeat: never. Last operation heartbeat from member: 2020-04-23 19:16:59.335. Invocation{op=com.hazelcast.map.impl.operation.GetOperation{serviceName='hz:impl:mapService', identityHash=300649867, partitionId=30, replicaIndex=0, callId=-10707, invocationTime=1587665497325 (2020-04-23 19:11:37.325), waitTimeout=-1, callTimeout=180000, name=ENRICHMENT-CACHE-DEFAULT}, tryCount=250, tryPauseMillis=500, invokeCount=1, callTimeoutMillis=180000, firstInvocationTimeMs=1587665656456, firstInvocationTime='2020-04-23 19:14:16.456', lastHeartbeatMillis=0, lastHeartbeatTime='1970-01-01 01:00:00.000', target=[10.195.40.212]:5701, pendingResponse={VOID}, backupsAcksExpected=0, backupsAcksReceived=0, connection=Connection[id=56, /10.195.40.210:5702->/10.195.40.212:60231, endpoint=[10.195.40.212]:5701, alive=true, type=MEMBER]}
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.experian.eda.ea.core.enrichmentpack.MultiThreadEnrichmentPackManager.evaluateAllPreEnrichmentRulesWithSizePopulator(MultiThreadEnrichmentPackManager.java:123)
... 90 common frames omitted
Caused by: com.hazelcast.core.OperationTimeoutException: GetOperation invocation failed to complete due to operation-heartbeat-timeout. Current time: 2020-04-23 19:17:37.414. Start time: 2020-04-23 19:14:16.456. Total elapsed time: 200958 ms. Last operation heartbeat: never. Last operation heartbeat from member: 2020-04-23 19:16:59.335. Invocation{op=com.hazelcast.map.impl.operation.GetOperation{serviceName='hz:impl:mapService', identityHash=300649867, partitionId=30, replicaIndex=0, callId=-10707, invocationTime=1587665497325 (2020-04-23 19:11:37.325), waitTimeout=-1, callTimeout=180000, name=ENRICHMENT-CACHE-DEFAULT}, tryCount=250, tryPauseMillis=500, invokeCount=1, callTimeoutMillis=180000, firstInvocationTimeMs=1587665656456, firstInvocationTime='2020-04-23 19:14:16.456', lastHeartbeatMillis=0, lastHeartbeatTime='1970-01-01 01:00:00.000', target=[10.195.40.212]:5701, pendingResponse={VOID}, backupsAcksExpected=0, backupsAcksReceived=0, connection=Connection[id=56, /10.195.40.210:5702->/10.195.40.212:60231, endpoint=[10.195.40.212]:5701, alive=true, type=MEMBER]}
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.newOperationTimeoutException(InvocationFuture.java:151)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolve(InvocationFuture.java:101)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolveAndThrowIfException(InvocationFuture.java:75)
at com.hazelcast.spi.impl.AbstractInvocationFuture.get(AbstractInvocationFuture.java:155)
at com.hazelcast.map.impl.proxy.MapProxySupport.invokeOperation(MapProxySupport.java:373)
at com.hazelcast.map.impl.proxy.MapProxySupport.getInternal(MapProxySupport.java:304)
at com.hazelcast.map.impl.proxy.MapProxyImpl.get(MapProxyImpl.java:114)
Here is the setting I use.
<map name="ENRICHMENT-CACHE-*">
<in-memory-format>BINARY</in-memory-format>
<backup-count>0</backup-count>
<max-idle-seconds>600</max-idle-seconds>
<eviction-policy>LRU</eviction-policy>
<max-size policy="PER_NODE">5000</max-size>
<eviction-percentage>25</eviction-percentage>
</map>
<properties>
<property name="hazelcast.logging.type">slf4j</property>
<property name="hazelcast.client.invocation.timeout.seconds">360</property>
<property name="hazelcast.operation.call.timeout.millis">180000</property>
</properties>
I see the code is written this way.
#Override
public final V get() throws InterruptedException, ExecutionException {
Object response = registerWaiter(Thread.currentThread(), null);
if (response != VOID) {
// no registration was done since a value is available.
return resolveAndThrowIfException(response);
}
boolean interrupted = false;
try {
for (; ; ) {
park();
if (isDone()) {
return resolveAndThrowIfException(state);
} else if (Thread.interrupted()) {
interrupted = true;
onInterruptDetected();
}
}
} finally {
restoreInterrupt(interrupted);
}
}
The current thread is parked, waiting for interruption. Could it be the heartbeat timeout exception interrupted the thread, and woke it in an errorneous state?
If yes, would increment of the hazelcast.max.no.heartbeat.seconds help?
If this is not the case, do you have any idea why the error occured & how to solve it?
Thank you.
Regards,
Khairul
i'm new to the fabric world and i'm testing the Java SDK in Fabric 1.4.
I've already set up a smart contract through Visual Studio Code and the fabric local env.
Now, I want to interact with it calling a smart contract endpoint via Java.
private Optional<FileAsset> sendTransaction(HFClient client, String functionToCall, String... args) {
Channel channel = client.getChannel(channelName);
TransactionProposalRequest tpr = TransactionProposalRequest.newInstance(client.getUserContext());
ChaincodeID fileChainCCId = ChaincodeID
.newBuilder()
.setName(chaincodeName)
.setVersion(chaincodeVersion)
.build();
tpr.setChaincodeID(fileChainCCId);
tpr.setChaincodeLanguage(Type.NODE);
tpr.setFcn(functionToCall).setArgs(args);
tpr.setProposalWaitTime(6_000);
log.info("Calling function: {} with args: {}", functionToCall, args);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); // Just
tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); // ditto
tm2.put("result", ":)".getBytes(UTF_8)); // This should be returned in
// the payload see chaincode
// why.
tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); // This should
// trigger an event
// see chaincode
// why.
try {
tpr.setTransientMap(tm2);
} catch (InvalidArgumentException e) {
log.error("Error setting transient map. Err: {}", e.getMessage());
return Optional.empty();
}
Collection<ProposalResponse> responses = null;
try {
responses = channel.sendTransactionProposal(tpr, channel.getPeers());
} catch (ProposalException | InvalidArgumentException e) {
log.error("Error sending transaction proposal: {}. Err: {}", tpr, e.getMessage());
return Optional.empty();
}
List<ProposalResponse> invalid = responses.stream().filter(r -> r.isInvalid()).collect(Collectors.toList());
if (!invalid.isEmpty()) {
invalid.forEach(response -> {
log.error(response.getMessage());
});
return Optional.empty();
}
List<ProposalResponse> resps = responses.stream()
.filter(r -> r.getStatus().equals(ProposalResponse.Status.SUCCESS)).collect(Collectors.toList());
resps.stream().forEach(resp -> {
log.info("Successful transaction proposal response Txid: {} from peer {}", resp.getTransactionID(),
resp.getPeer().getName());
});
try {
Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(responses);
if (proposalConsistencySets.size() != 1) {
log.error("Expected only one set of consistent proposal responses but got {}",
proposalConsistencySets.size());
return Optional.empty();
}
} catch (InvalidArgumentException e) {
log.error("Error generating proposal consistency sets. Err: {}", e.getMessage());
return Optional.empty();
}
// If all responses are fine, then we can proceed with sending the
// transaction to an orderer
CompletableFuture<TransactionEvent> sentTransaction = channel.sendTransaction(resps, channel.getOrderers(), client.getUserContext());
// For simplicity, we just request result with a timeout and verify that
// for validity.
BlockEvent.TransactionEvent event = null;
try {
event = sentTransaction.get(60, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("Error sending transaction to orders. Err: {}", e.getMessage());
return Optional.empty();
}
if (event.isValid()) {
log.info("Transacion tx: " + event.getTransactionID() + " is completed.");
} else {
log.error("Transaction tx: " + event.getTransactionID() + " is invalid.");
}
return Optional.empty();
}
On
CompletableFuture<TransactionEvent> sentTransaction = channel.sendTransaction(resps, channel.getOrderers(), client.getUserContext());
I get the following error:
UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
2019-05-08 18:49:00.761 ERROR 15748 --- [ault-executor-0] o.hyperledger.fabric.sdk.OrdererClient : OrdererClient{id: 7, channel: mychannel, name: peer0.org1.example.com, url: grpc://localhost:17051} managed channel isTerminated: false, isShutdown: false, state: READY
2019-05-08 18:49:00.768 ERROR 15748 --- [ault-executor-0] o.hyperledger.fabric.sdk.OrdererClient : Received error org.hyperledger.fabric.sdk.OrdererClient$1#326e7643 UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
io.grpc.StatusRuntimeException: UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
at io.grpc.Status.asRuntimeException(Status.java:530) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:434) [grpc-stub-1.17.1.jar:1.17.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.CensusStatsModule$StatsClientInterceptor$1$1.onClose(CensusStatsModule.java:694) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.CensusTracingModule$TracingClientInterceptor$1$1.onClose(CensusTracingModule.java:397) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:459) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:63) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:546) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$600(ClientCallImpl.java:467) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:584) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) [grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123) [grpc-core-1.17.1.jar:1.17.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_152]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_152]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_152]
2019-05-08 18:49:00.769 ERROR 15748 --- [ main] o.hyperledger.fabric.sdk.OrdererClient : OrdererClient{id: 7, channel: mychannel, name: peer0.org1.example.com, url: grpc://localhost:17051} grpc status Code:unknown service orderer.AtomicBroadcast, Description UNIMPLEMENTED,
2019-05-08 18:49:00.770 ERROR 15748 --- [ main] o.hyperledger.fabric.sdk.OrdererClient : OrdererClient{id: 7, channel: mychannel, name: peer0.org1.example.com, url: grpc://localhost:17051}sendTransaction error Channel mychannel, send transaction failed on orderer OrdererClient{id: 7, channel: mychannel, name: peer0.org1.example.com, url: grpc://localhost:17051}. Reason: UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
org.hyperledger.fabric.sdk.exception.TransactionException: Channel mychannel, send transaction failed on orderer OrdererClient{id: 7, channel: mychannel, name: peer0.org1.example.com, url: grpc://localhost:17051}. Reason: UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
at org.hyperledger.fabric.sdk.OrdererClient.sendTransaction(OrdererClient.java:236) ~[fabric-sdk-java-1.4.1.jar:na]
at org.hyperledger.fabric.sdk.Orderer.sendTransaction(Orderer.java:161) [fabric-sdk-java-1.4.1.jar:na]
at org.hyperledger.fabric.sdk.Channel.sendTransaction(Channel.java:4971) [fabric-sdk-java-1.4.1.jar:na]
at org.hyperledger.fabric.sdk.Channel.sendTransaction(Channel.java:4504) [fabric-sdk-java-1.4.1.jar:na]
at it.blockchain.fabric.service.impl.FileChainSmartContractServiceImpl.sendTransaction(FileChainSmartContractServiceImpl.java:205) [classes/:na]
at it.blockchain.fabric.service.impl.FileChainSmartContractServiceImpl.addFileAsset(FileChainSmartContractServiceImpl.java:65) [classes/:na]
at it.blockchain.fabric.clr.DemoCLR.run(DemoCLR.java:40) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at it.blockchain.fabric.FilechainFabricDemoApplication.main(FilechainFabricDemoApplication.java:10) [classes/:na]
Caused by: io.grpc.StatusRuntimeException: UNIMPLEMENTED: unknown service orderer.AtomicBroadcast
at io.grpc.Status.asRuntimeException(Status.java:530) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:434) ~[grpc-stub-1.17.1.jar:1.17.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.CensusStatsModule$StatsClientInterceptor$1$1.onClose(CensusStatsModule.java:694) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.CensusTracingModule$TracingClientInterceptor$1$1.onClose(CensusTracingModule.java:397) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:459) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:63) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:546) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$600(ClientCallImpl.java:467) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:584) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) ~[grpc-core-1.17.1.jar:1.17.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123) ~[grpc-core-1.17.1.jar:1.17.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_152]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_152]
at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_152]
2019-05-08 18:49:00.771 ERROR 15748 --- [ main] org.hyperledger.fabric.sdk.Channel : Channel mychannel unsuccessful sendTransaction to orderer peer0.org1.example.com (grpc://localhost:17051)
Any suggetions about how to resolve it?
You are targeting a peer for AtomicBroadcast - peer0.org1.example.com
you need to target an orderer. seems like your network configuration is wrong.
I have a simple Gradle Spring Boot (v 1.3.3) WebMVC application I'm running from the command line via "Gradle bootrun". I am also including Spring Security and am overriding some default security configuration by including a java security config class. My build file is
buildscript {
ext {
springBootVersion = '1.3.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
baseName = 'readinglist'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-security")
runtime('com.h2database:h2')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.9'
}
My security configuration class is
package readinglist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ReaderRepository readerRepository;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/readingList").access("hasRole('READER')")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/"); // Added .and()....logoutSuccessURL()
}
#Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(new UserDetailsService() {
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
UserDetails userDetails = readerRepository.findOne(username);
if (userDetails != null) {
return userDetails;
}
throw new UsernameNotFoundException("User '" + username + "' not found.");
}
});
}
}
I also have a home controller that maps the URL "/" to the view home.html
When I run the application and go to localhost:8080/ I get the home page.
When I try to access the URL "/readingList", I get the custom login page. If I enter incorrect credentials, I return to the login page for another try. If I enter valid credentials I get the readingList page. So far so good. The problem is with the logoutSuccessURL("/"). When I go to the URL "/logout" this should log me out and take me back to "/", but instead I get the following error showing in the browser:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Mar 03 19:31:24 PST 2016
There was an unexpected error (type=Not Found, status=404).
No message available
I turned on debug for security and when I hit my logout link I get the following:
2016-03-03 19:48:45.033 DEBUG 22401 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2016-03-03 19:48:45.033 DEBUG 22401 --- [io-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2016-03-03 19:48:45.036 DEBUG 22401 --- [io-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2016-03-03 19:48:45.036 DEBUG 22401 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
2016-03-03 19:48:45.046 DEBUG 22401 --- [io-8080-exec-10] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
2016-03-03 19:48:45.047 DEBUG 22401 --- [io-8080-exec-10] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#7ae1a0fb] based on requested media type 'text/html'
2016-03-03 19:48:45.047 DEBUG 22401 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#7ae1a0fb] in DispatcherServlet with name 'dispatcherServlet'
2016-03-03 19:48:45.055 DEBUG 22401 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Successfully completed request
I'm not sure why DispatcherServlet is trying to lookup "/error". I am also not being logged out since if I try to go to the URL "/readingList" again, I am not prompted for credentials.
I did a little more testing by loggin in, then going to the URL "/logout" manually. I got the following in my log:
2016-03-04 16:39:31.170 DEBUG 24395 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : /logout reached end of additional filter chain; proceeding with original chain
2016-03-04 16:39:31.170 DEBUG 24395 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/logout]
2016-03-04 16:39:31.170 DEBUG 24395 --- [nio-8080-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /logout
2016-03-04 16:39:31.171 DEBUG 24395 --- [nio-8080-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/logout]
2016-03-04 16:39:31.171 DEBUG 24395 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/logout] are [/**]
2016-03-04 16:39:31.171 DEBUG 24395 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/logout] are {}
2016-03-04 16:39:31.172 DEBU G 24395 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/logout] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#e146f93]]] and 1 interceptor
2016-03-04 16:39:31.172 DEBUG 24395 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/logout] is: -1
2016-03-04 16:39:31.172 DEBUG 24395 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-03-04 16:39:31.173 DEBUG 24395 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Successfully completed request
2016-03-04 16:39:31.173 DEBUG 24395 --- [nio-8080-exec-6] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2016-03-04 16:39:31.173 DEBUG 24395 --- [nio-8080-exec-6] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2016-03-04 16:39:31.196 DEBUG 24395 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
....
It seems like the "/logout" URL is not working which I don't undertand. I though the default logout URL is "/logout".
I found a solution in a similar project here, http://spr.com/part-5-integrating-spring-security-with-spring-boot-web/. In my security config I changed
.logout()
.logoutSuccessUrl("/")
.and()
...
to
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.and()
...
I'm not sure if this is the "preferred" solution, and I don't know why the call to logoutRequestMatcher(...) is needed. I have other (non-Spring-Boot) Spring Security projects that don't use the call to logoutRequestMatcher(...), and the .logout(...).logoutSuccessUrl(...) call works just fine.
.and()
.logout()
.invalidateHttpSession(true)
.logoutUrl("/logout")
.permitAll();
i prefer this solution because it wipe the session data so you can't access anymore try it yousrself to make sure open the developer tools in the browser and see the session !!