solacesamples / solace-samples-java-jcsmp Goto Github PK
View Code? Open in Web Editor NEWGetting Started Samples for the Solace JCSMP Java API.
Home Page: https://tutorials.solace.dev/jcsmp
License: Apache License 2.0
Getting Started Samples for the Solace JCSMP Java API.
Home Page: https://tutorials.solace.dev/jcsmp
License: Apache License 2.0
The samples would be slightly improved if they used the @OverRide annotation when implementing the message listener and producer callback interfaces.
Based on PRs from older JCSMP repo by https://github.com/clubanderson, include a snippet to demonstrate how to connect with TLS and specifying a truststore.
Refs:
I've started a solace-pubsub-standard docker container using the example at https://docs.solace.com/Solace-SW-Broker-Set-Up/Docker-Containers/Set-Up-Single-Linux-Container.htm
$ docker run -d -p 8080:8080 -p 55555:55555 --shm-size=2g --env username_admin_globalaccesslevel=admin --env username_admin_password=admin --name=solace solace/solace-pubsub-standard
And then I'm trying to connect to that container using code from https://solace.com/samples/solace-samples-semp/messagevpn-with-queue-python/
import semp_client
semp_client.configuration.host = "localhost"
semp_client.configuration.username = "admin"
semp_client.configuration.password = "admin"
api_instance = semp_client.MsgVpnApi()
# Create message-vpn
msg_vpn = semp_client.MsgVpn()
msg_vpn.msg_vpn_name = "message_vpn_name"
msg_vpn.authentication_basic_type = "internal"
msg_vpn.max_msg_spool_usage = 1500
msg_vpn.enabled = True
api_instance.create_msg_vpn(msg_vpn)
And it keeps trying to connect to:
//////////////////////////////////////////////////
http://www.solace.com/SEMP/v2/config/msgVpns
{'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'Swagger-Codegen/1.0.0/python', 'Authorization': 'Basic Og=='}
[]
[]
{'authenticationBasicType': 'internal', 'enabled': True, 'maxMsgSpoolUsage': 1500, 'msgVpnName': 'message_vpn_name'}
True
None
//////////////////////////////////////////////////
I dont understand why it is trying to connect to www.solace.com
when I explicitly set semp_client.configuration.host
to localhost
.
What am I missing?
Error in question:
$ ./gradlew assemble
./gradlew: line 2: $'\r': command not found
./gradlew: line 8: $'\r': command not found
./gradlew: line 36: syntax error near unexpected token `$'{\r''
'/gradlew: line 36: `warn ( ) {
Can be fixed using unix2dos.exe
Gradlew fails with java 9.0.1
./gradlew assemble
FAILURE: Build failed with an exception.
What went wrong:
Could not determine java version from '9.0.1'.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Looks like someone forgot to replace the default "solace-samples-template" with "solace-samples-java" in the CONTRIBUTING.md file. Made for some confusion as a first-time GitHub contributor.
Also noticed this in some other SolaceSamples projects (e.g. Node.js, C, etc.), but not all (e.g. the JavaScript one is ok).
When TopicPublisher publish a message,TopicSubscriber connection was forcibly closed.And the error is "An existing connection was forcibly closed by the remote host".
I am trying to programmatically create a MsgVpn
using Java. I've written a small JUnit5 test using some example code that I found in this github.
The test spins up a docker container running solace/solace-pubsub-standard
with some basic credentials, and then initialize()
s a sempApiInstance
, and uses it to createMessageVpn()
just as the example code at https://github.com/SolaceSamples/solace-samples-semp/blob/master/java/src/main/java/com/solace/samples/ManageVPN.java does.
However, instead of getting a MsgVpnResponse
I get an exception. It appears to be looking for an alias, but I'm not sure what that is precisely, or what value to provide.
Here is the exception:
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{
"meta":{
"error":{
"code":11,
"description":"Problem with alias: Got value `None` of type `null`. Value must be of type(s): `('string',)`",
"status":"INVALID_PARAMETER"
},
"request":{
"method":"POST",
"uri":"http://localhost:32825/SEMP/v2/config/msgVpns"
},
"responseCode":400
}
}]
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:101)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:184)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:651)
at io.swagger.client.ApiClient.invokeAPI(ApiClient.java:512)
at io.swagger.client.api.MsgVpnApi.createMsgVpn(MsgVpnApi.java:211)
at com.example.demo.CreateNewMessageVpnTests.createMessageVpn(CreateNewMessageVpnTests.java:50)
at com.example.demo.CreateNewMessageVpnTests.test(CreateNewMessageVpnTests.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
And here is my JUnit5 Test
package com.example.demo;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.client.RestClientException;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import io.swagger.client.ApiClient;
import io.swagger.client.api.MsgVpnApi;
import io.swagger.client.model.MsgVpn;
import io.swagger.client.model.MsgVpn.AuthenticationBasicTypeEnum;
import io.swagger.client.model.MsgVpnResponse;
@SpringBootTest
@Testcontainers
class CreateNewMessageVpnTests {
@SuppressWarnings("rawtypes")
@Container
public GenericContainer solace = new GenericContainer("solace/solace-pubsub-standard")
.withEnv("username_admin_globalaccesslevel", "admin").withEnv("username_admin_password", "admin")
.withSharedMemorySize(2L * 1024L * 1024L * 1024L).withExposedPorts(55555, 8080);
MsgVpnApi sempApiInstance;
public void initialize(String basePath, String user, String password) throws Exception {
System.out.format("SEMP initializing: %s, %s \n", basePath, user);
ApiClient thisClient = new ApiClient();
thisClient.setBasePath(basePath);
thisClient.setUsername(user);
thisClient.setPassword(password);
sempApiInstance = new MsgVpnApi(thisClient);
}
public MsgVpnResponse createMessageVpn(String messageVpnName) throws RestClientException {
System.out.format("Creating Message-VPN: %s...\n", messageVpnName);
// Create message-vpn
MsgVpn msgVpn = new MsgVpn();
msgVpn.setMsgVpnName(messageVpnName);
msgVpn.setAuthenticationBasicType(AuthenticationBasicTypeEnum.INTERNAL);
msgVpn.setMaxMsgSpoolUsage(1500L);
msgVpn.setEnabled(true);
MsgVpnResponse resp = sempApiInstance.createMsgVpn(msgVpn, null, null);
return resp;
}
@Test
void test() throws Exception {
initialize(String.format("http://%s:%d/SEMP/v2/config", solace.getHost(), solace.getMappedPort(8080)), "admin",
"admin");
MsgVpnResponse msgVpnResponse = createMessageVpn("messageVpnName");
}
}
Lack of capabilities to set timestamp. Can we add this to sample codes?
The README.md is not properly rendered and contains markup:
The "Getting Started" tutorials will get you up to speed and sending messages with Solace technology as quickly as possible. There are three ways you can get started:
Follow [these instructions]({{ site.links-solaceCloud-setup }}){:target="_top"} to quickly spin up a cloud-based Solace messaging service for your applications.
Follow [these instructions]({{ site.docs-vmr-setup }}){:target="_top"} to start the Solace VMR in leading Clouds, Container Platforms or Hypervisors. The tutorials outline where to download and how to install the Solace VMR.
If your company has Solace message routers deployed, contact your middleware team to obtain the host name or IP address of a Solace message router to test against, a username and password to access it, and a VPN in which you can produce and consume messages.
This applies to most other samples README.md too.
You will need not the SMF URL for the example, but also the username and password so that should be noted to be precise. (Unless authentication is disabled, but that to me would contradict the assumption of an enabled client username and password
Hit this particular exception when running on a VMR. Temporary queue still exists, and the last message (Message number 5) is still in the queue.
wari@box:~/src/solace-samples-java$ ./build/staged/bin/topicToQueueMapping 192.168.29.133
TopicToQueueMapping initializing...
Sep 16, 2016 10:58:39 AM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connecting to host 'orig=192.168.29.133, host=192.168.29.133' (host 1 of 1, smfclient 2, attempt 1 of 1, this_host_attempt: 1 of 1)
Sep 16, 2016 10:58:39 AM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connected to host 'orig=192.168.29.133, host=192.168.29.133' (smfclient 2)
All required capabilities supported!
Provision queue 'Q/tutorial/topicToQueueMapping' on the appliance...Producer received response for msg ID #2
Producer received response for msg ID #4
Producer received response for msg ID #6
Producer received response for msg ID #8
Sent messages.
Producer received response for msg ID #10
TextMessage received: 'Message number 1'
Message Dump:
Destination: Topic 'T/mapped/topic/sample'
Class Of Service: USER_COS_1
DeliveryMode: PERSISTENT
Message Id: 17670
Binary Attachment: len=19
1c 13 4d 65 73 73 61 67 65 20 6e 75 6d 62 65 72 ..Message.number
20 31 00 .1.
.... CUT ...
TextMessage received: 'Message number 5'
Message Dump:
Destination: Topic 'T/mapped/topic/sample'
Class Of Service: USER_COS_1
DeliveryMode: PERSISTENT
Message Id: 17674
Binary Attachment: len=19
1c 13 4d 65 73 73 61 67 65 20 6e 75 6d 62 65 72 ..Message.number
20 35 00 .5.
Sep 16, 2016 10:58:40 AM com.solacesystems.jcsmp.impl.JCSMPXMLMessage ackMessage
WARNING: ackMessage is ignored because the message acknowledgement mode is auto-ack
Finished consuming expected messages.
Sep 16, 2016 10:58:40 AM com.solacesystems.jcsmp.impl.flow.FlowHandleImpl triggerAsyncDelivery
WARNING: Exception occurred in async delivery for flow 18
java.lang.IllegalStateException: Attempted an operation on a closed message consumer.
at com.solacesystems.jcsmp.impl.flow.FlowHandleImpl.ackMessage(FlowHandleImpl.java:1766)
at com.solacesystems.jcsmp.impl.flow.FlowHandleImpl.triggerAsyncDelivery(FlowHandleImpl.java:1449)
at com.solacesystems.jcsmp.protocol.nio.impl.ConsumerMessageNotification.handleNotification(ConsumerMessageNotification.java:22)
at com.solacesystems.jcsmp.protocol.nio.impl.ConsumerNotificationDispatcher.eventLoop(ConsumerNotificationDispatcher.java:112)
at com.solacesystems.jcsmp.protocol.nio.impl.ConsumerNotificationDispatcher.run(ConsumerNotificationDispatcher.java:130)
at java.lang.Thread.run(Thread.java:745)
Sep 16, 2016 10:58:40 AM com.solacesystems.jcsmp.impl.RequestResponseTask startTimer
INFO: RequestResponseTask: skipped startTimer(), timeout:10000 startTimerFlag:false
Exiting.
Sep 16, 2016 10:58:40 AM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel close
INFO: Channel Closed (smfclient 2)
Consumer received exception: com.solacesystems.jcsmp.JCSMPException: Error calling XMLMessagelistener
Should be updated to "PubSub+ software broker" or something.
In order to facilitate various branching strategies we may need as we release updates samples to match new Solace Messaging for PCF releases, it would be good to take advantage of the new GitHub pages feature of hosting in the docs subdirectory.
It would be nice to illustrate how to connect securely to Solace Message Routers. I believe the solution to this would be in two parts.
Some of the details that need to be explained are covered in Solace documentation here:
Let's do this first in the Java API, once done we can look at porting this sample to the other Solace APIs.
Check the JCSMP implementation from this sample:
So we used this sync method with exception handler and still lost the message during out tests. A strange sleep which is not acceptable for prod for 1,5 seconds and some comment leave you in an unclear situation what for that is in the sample.
https://github.com/SolaceSamples/solace-samples-java-jcsmp/blob/ba8ae0cfc921b9307fb7b36b80f9cd6bb3817998/src/main/java/com/solace/samples/jcsmp/patterns/GuaranteedPublisher.java#L151C6-L151C81
The warning:
The Task.leftShift(Closure) method has been deprecated. This is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
at build_30qizzagbwlt1wxmux037y9uy.run(/mnt/c/Users/AaronLee/Downloads/solace-samples-java-master/build.gradle:53)
caused by:
task createAllStartScripts() << {
// just a placeholder
}
So appears unnecessary.
It's pretty easy to enhance the TopicSubscriber sample so that it can retrieve the first message from a SolCache cluster:
// Add Cache handling
// Requests the most recent message on the topic, using default timeout 10sec
CacheSessionProperties props = new CacheSessionProperties(cacheName);
CacheSession cacheSession;
try {
cacheSession = session.createCacheSession(props);
cacheSession.sendCacheRequest(1L, topic, false, CacheLiveDataAction.FULFILL);
} catch (JCSMPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There doesn't seem to be any sample online available which shows this.
All of the basic samples force a password to be passed in on the command line. This is not ideal when first connecting to the Software broker that has the default
VPN and default
client-username enabled, and no password is required.
I'm happy to do the fix myself, to get practice with GitHub's contributing methods.
Note: this doesn't apply to the features ones, which look to be taken from the API's original examples.
Hi Team,
I think we have issue with documentation in Persistence with Queues
In section Sending a message to a queue
we are creating topic as below whereas we should be creating Queue
final Topic topic = JCSMPFactory.onlyInstance().createTopic("tutorial/topic");
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.