Popular New Releases in Websocket
ws
websocket
Minor new features and maintenance update
websocketd
January 24, 2021
koel
v5.1.14
NodeBB
v1.19.6
Popular Libraries in Websocket
by netty java
29020 Apache-2.0
Netty project - an event-driven asynchronous network application framework
by websockets javascript
17955 MIT
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
by gorilla go
16419 BSD-2-Clause
A fast, well-tested and widely used WebSocket implementation for Go.
by joewalnes go
15599 BSD-2-Clause
Turn any program that uses STDIN/STDOUT into a WebSocket server. Like inetd, but for WebSockets.
by koel php
13513 MIT
🐦 A personal music streaming server that works.
by NodeBB javascript
12541 GPL-3.0
Node.js based forum software built for the modern web
by rrweb-io typescript
11468 MIT
record and replay the web
by walkor php
9594 MIT
An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols. PHP>=5.3.
by TooTallNate java
8896 MIT
A barebones WebSocket client and server implementation written in 100% Java.
Trending New libraries in Websocket
by OpenIMSDK go
7570 Apache-2.0
OpenIM: Instant messaging open source project based on go built by IM technology experts. Backend in Go.(由IM技术专家打造的基于 Go 实现的即时通讯(IM)项目,从服务端到客户端SDK开源即时通讯(IM)整体解决方案,可以轻松替代第三方IM云服务,打造具备聊天、社交功能的app。)
by GRVYDEV rust
3308 MIT
A self contained OBS -> FTL -> WebRTC live streaming server. Comprised of 3 parts once configured anyone can achieve sub-second OBS to the browser livestreaming
by jetlinks java
2534 Apache-2.0
JetLinks 基于Java8,Spring Boot 2.x ,WebFlux,Netty,Vert.x,Reactor等开发, 是一个全响应式的企业级物联网平台。支持统一物模型管理,多种设备,多种厂家,统一管理。统一设备连接管理,多协议适配(TCP,MQTT,UDP,CoAP,HTTP等),屏蔽网络编程复杂性,灵活接入不同厂家不同协议等设备。实时数据处理,设备告警,消息通知,数据转发。地理位置,数据可视化等。能帮助你快速建立物联网相关业务系统。
by livekit go
2370 Apache-2.0
Scalable, high-performance WebRTC SFU. SDKs in JS, React, Flutter, Swift, Kotlin, Go, Ruby and Node.
by Snailclimb java
1633 NOASSERTION
A custom RPC framework implemented by Netty+Kyro+Zookeeper.(一款基于 Netty+Kyro+Zookeeper 实现的自定义 RPC 框架-附详细实现过程和相关教程。)
by bradtraversy html
724
Realtime chat app with rooms
by lemunozm rust
668 Apache-2.0
Fast and easy-to-use event-driven network library.
by fuzhengwei javascript
598 Apache-2.0
:performing_arts: 本项目是作者小傅哥使用JavaFx、Netty4.x、SpringBoot、Mysql等技术栈和偏向于DDD领域驱动设计方式,搭建的仿桌面版微信实现通信核心功能。课程文章已发布到GitChat专栏,欢迎购买。如果本项目能为您提供帮助,请给予支持(关注、:star:Star、分享)!
by ErickWendel javascript
546
Exemplos de código da segunda semana Javascript Expert - Zoom Clone
Top Authors in Websocket
1
12 Libraries
104
2
10 Libraries
6550
3
9 Libraries
774
4
9 Libraries
6227
5
9 Libraries
3692
6
8 Libraries
316
7
8 Libraries
6173
8
8 Libraries
8113
9
8 Libraries
240
10
7 Libraries
9602
1
12 Libraries
104
2
10 Libraries
6550
3
9 Libraries
774
4
9 Libraries
6227
5
9 Libraries
3692
6
8 Libraries
316
7
8 Libraries
6173
8
8 Libraries
8113
9
8 Libraries
240
10
7 Libraries
9602
Trending Kits in Websocket
Here are some of the famous Python WebSocket Utilities Libraries. Some use cases of Python WebSocket Utilities Libraries include Real-time Chat and Messaging Applications, Online Gaming, IoT Applications, and Real-time Data Visualization and Dashboards.
Python WebSocket utilities libraries are collections of code that provide a set of utilities to help developers create and manage WebSocket connections in Python. These libraries typically provide methods to simplify WebSocket connection setup, message sending, message receiving and connection management. They can also provide additional features such as authentication and SSL/TLS support.
Let us have a look at some of these libraries in detail below.
tornado
- Can handle up to 10,000 simultaneous open connections, making it ideal for applications with high levels of concurrent users.
- Can handle multiple requests simultaneously without blocking requests.
- One of the few web frameworks that supports WebSocket connections.
gevent
- Based on greenlet and libevent, making it extremely fast, lightweight and efficient.
- Highly extensible and can be easily integrated with other Python libraries and frameworks.
- Provides a high level of concurrency, allowing multiple requests to be handled at the same time.
twisted
- Event-driven architecture makes it easy to build highly concurrent applications.
- Can be used to build distributed applications, which can be used to connect multiple machines over the network.
- Provides a low-level interface which makes it easier to work with websockets.
websockets
- Data can be sent and received quickly, allowing for real-time communication.
- Enable bidirectional communication between the client and the server.
- Use the secure websocket protocol (WSS) which encrypts all data sent over the connection.
websocket-client
- Built on top of the standard library's asyncio module, which allows for asynchronous communication with websockets.
- Supports secure websocket connections via TLS/SSL, as well as binary messages and fragmented messages.
- Supports custom headers and subprotocols, making it easy to communicate with specific services that require specific headers or subprotocols.
WebSocket-for-Python
- Supports multiple protocols such as WebSocket, HTTP, and TCP, allowing for more flexible usage.
- Has built-in security features such as authentication and encryption, allowing you to securely communicate with other applications.
- Is written in Python, making it easy to use and integrate with existing Python applications.
socketIO-client
- Supports multiple transports, including long polling, WebSockets and cross-browser support.
- Support for namespaces, allowing for multiple independent connections to the same server.
- Allows for subscribing to multiple events, allowing for a more efficient implementation of your application.
pywebsocket
- Supports both server-side and client-side websocket connections.
- Provides support for websocket extensions.
- Supports both connection-oriented and connectionless websockets, making it a versatile tool for developers.
Trending Discussions on Websocket
How can Bloc listen to stream and emit state
PIP failed to build package cytoolz
IntelliJ - Invalid source release: 17
NestJS GraphQL subscriptions not working with `graphql-ws`
WebSocket not working when trying to send generated answer by keras
Prevent unauthorized http requests redirected to /error from setting session cookie - spring boot - spring security
How to give certificate to Java Websocket?
Jenkins with Kubernetes Client Plugin - NoSuchMethodError
Activiti 6.0.0 UI app / in-memory H2 database in tomcat9 / java version "9.0.1"
Split payload from JSON String
QUESTION
How can Bloc listen to stream and emit state
Asked 2022-Mar-31 at 23:58In my flutter app, I use flutter_bloc for state management.
The bloc
in question uses a repository
. The repository
subscribes to a websocket, and new data is added to a stream.
Problem: My bloc listens to the stream:
1InvestmentClubBloc({
2 required this.investmentClubRepository
3 }) : super(InvestmentClubLoading()) {
4 onChangeSubscription = investmentClubRepository.onNewMessage.listen(
5 (event) {
6 emit(NewMessageState(event); // <-- The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test
7 },
8 );
9 }
10
The problem is that emit
does not work (I get the warning "The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test")
How can bloc listen to a stream and emit new states depending on stream events?
ANSWER
Answered 2021-Dec-06 at 10:53You should use emit
in eventHandler
, use below code to complete your task:
1InvestmentClubBloc({
2 required this.investmentClubRepository
3 }) : super(InvestmentClubLoading()) {
4 onChangeSubscription = investmentClubRepository.onNewMessage.listen(
5 (event) {
6 emit(NewMessageState(event); // <-- The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test
7 },
8 );
9 }
10abstract class Event {}
11
12class DemoEvent extends Event {}
13
14var fakeStream =
15 Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15);
16
17class DemoBloc extends Bloc<Event, int> {
18 DemoBloc() : super(0) {
19 fakeStream.listen((_) {
20 // add your event here
21 add(DemoEvent());
22 });
23 on<DemoEvent>((_, emit) {
24 // emit new state
25 emit(state + 1);
26 });
27 }
28}
29
QUESTION
PIP failed to build package cytoolz
Asked 2022-Mar-26 at 18:26I'm trying to install eth-brownie using 'pipx install eth-brownie' but I get an error saying
1pip failed to build package: cytoolz
2Some possibly relevant errors from pip install:
3 build\lib.win-amd64-3.10\cytoolz\functoolz.cp310-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals
4 error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120
5
I've had a look at the log file and it shows that it failed to build cytoolz. It also mentions "ALERT: Cython not installed. Building without Cython.". From my limited understanding Cytoolz is apart of Cython so i think the reason why the installation for eth-brownie failed is because it could not build cytoolz as it was trying to build it without Cython. The thing is I already have cython installed:
1pip failed to build package: cytoolz
2Some possibly relevant errors from pip install:
3 build\lib.win-amd64-3.10\cytoolz\functoolz.cp310-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals
4 error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120
5C:\Users\alaiy>pip install cython
6Requirement already satisfied: cython in c:\python310\lib\site-packages (0.29.24)
7
Extract from the log file (I can paste the whole thing but its lengthy):
1pip failed to build package: cytoolz
2Some possibly relevant errors from pip install:
3 build\lib.win-amd64-3.10\cytoolz\functoolz.cp310-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals
4 error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120
5C:\Users\alaiy>pip install cython
6Requirement already satisfied: cython in c:\python310\lib\site-packages (0.29.24)
7Building wheels for collected packages: bitarray, cytoolz, lru-dict, parsimonious, psutil, pygments-lexer-solidity, varint, websockets, wrapt
8 Building wheel for bitarray (setup.py): started
9 Building wheel for bitarray (setup.py): finished with status 'done'
10 Created wheel for bitarray: filename=bitarray-1.2.2-cp310-cp310-win_amd64.whl size=55783 sha256=d4ae97234d659ed9ff1f0c0201e82c7e321bd3f4e122f6c2caee225172e7bfb2
11 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\1d\29\a8\5364620332cc833df35535f54074cf1e51f94d07d2a660bd6d
12 Building wheel for cytoolz (setup.py): started
13 Building wheel for cytoolz (setup.py): finished with status 'error'
14 Running setup.py clean for cytoolz
15 Building wheel for lru-dict (setup.py): started
16 Building wheel for lru-dict (setup.py): finished with status 'done'
17 Created wheel for lru-dict: filename=lru_dict-1.1.7-cp310-cp310-win_amd64.whl size=12674 sha256=6a7e7b2068eb8481650e0a2ae64c94223b3d2c018f163c5a0e7c1d442077450a
18 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\47\0a\dc\b156cb52954bbc1c31b4766ca3f0ed9eae9b218812bca89d7b
19 Building wheel for parsimonious (setup.py): started
20 Building wheel for parsimonious (setup.py): finished with status 'done'
21 Created wheel for parsimonious: filename=parsimonious-0.8.1-py3-none-any.whl size=42724 sha256=f9235a9614af0f5204d6bb35b8bd30b9456eae3021b5c2a9904345ad7d07a49d
22 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\b1\12\f1\7a2f39b30d6780ae9f2be9a52056595e0d97c1b4531d183085
23 Building wheel for psutil (setup.py): started
24 Building wheel for psutil (setup.py): finished with status 'done'
25 Created wheel for psutil: filename=psutil-5.8.0-cp310-cp310-win_amd64.whl size=246135 sha256=834ab1fd1dd0c18e574fc0fbf07922e605169ac68be70b8a64fb90c49ad4ae9b
26 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\12\a3\6d\615295409067d58a62a069d30d296d61d3ac132605e3a9555c
27 Building wheel for pygments-lexer-solidity (setup.py): started
28 Building wheel for pygments-lexer-solidity (setup.py): finished with status 'done'
29 Created wheel for pygments-lexer-solidity: filename=pygments_lexer_solidity-0.7.0-py3-none-any.whl size=7321 sha256=46355292f790d07d941a745cd58b64c5592e4c24357f7cc80fe200c39ab88d32
30 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\36\fd\bc\6ff4fe156d46016eca64c9652a1cd7af6411070c88acbeabf5
31 Building wheel for varint (setup.py): started
32 Building wheel for varint (setup.py): finished with status 'done'
33 Created wheel for varint: filename=varint-1.0.2-py3-none-any.whl size=1979 sha256=36b744b26ba7534a494757e16ab6e171d9bb60a4fe4663557d57034f1150b678
34 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\39\48\5e\33919c52a2a695a512ca394a5308dd12626a40bbcd288de814
35 Building wheel for websockets (setup.py): started
36 Building wheel for websockets (setup.py): finished with status 'done'
37 Created wheel for websockets: filename=websockets-9.1-cp310-cp310-win_amd64.whl size=91765 sha256=a00a9c801269ea2b86d72c0b0b654dc67672519721afeac8f912a157e52901c0
38 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\79\f7\4e\873eca27ecd6d7230caff265283a5a5112ad4cd1d945c022dd
39 Building wheel for wrapt (setup.py): started
40 Building wheel for wrapt (setup.py): finished with status 'done'
41 Created wheel for wrapt: filename=wrapt-1.12.1-cp310-cp310-win_amd64.whl size=33740 sha256=ccd729b6e3915164ac4994aef731f21cd232466b3f6c4823c9fda14b07e821c3
42 Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\8e\61\d3\d9e7053100177668fa43216a8082868c55015f8706abd974f2
43Successfully built bitarray lru-dict parsimonious psutil pygments-lexer-solidity varint websockets wrapt
44Failed to build cytoolz
45Installing collected packages: toolz, eth-typing, eth-hash, cytoolz, six, pyparsing, eth-utils, varint, urllib3, toml, rlp, pyrsistent, pycryptodome, py, pluggy, parsimonious, packaging, netaddr, multidict, iniconfig, idna, hexbytes, eth-keys, colorama, charset-normalizer, certifi, base58, attrs, atomicwrites, yarl, typing-extensions, requests, python-dateutil, pytest, multiaddr, jsonschema, inflection, eth-rlp, eth-keyfile, eth-abi, chardet, bitarray, async-timeout, websockets, wcwidth, tomli, sortedcontainers, semantic-version, regex, pywin32, pytest-forked, pyjwt, pygments, protobuf, platformdirs, pathspec, mythx-models, mypy-extensions, lru-dict, ipfshttpclient, execnet, eth-account, dataclassy, click, asttokens, aiohttp, wrapt, web3, vyper, vvm, tqdm, pyyaml, pythx, python-dotenv, pytest-xdist, pygments-lexer-solidity, py-solc-x, py-solc-ast, psutil, prompt-toolkit, lazy-object-proxy, hypothesis, eth-event, eip712, black, eth-brownie
46 Running setup.py install for cytoolz: started
47 Running setup.py install for cytoolz: finished with status 'error'
48
49PIP STDERR
50----------
51WARNING: The candidate selected for download or install is a yanked version: 'protobuf' candidate (version 3.18.0 at https://files.pythonhosted.org/packages/74/4e/9f3cb458266ef5cdeaa1e72a90b9eda100e3d1803cbd7ec02f0846da83c3/protobuf-3.18.0-py2.py3-none-any.whl#sha256=615099e52e9fbc9fde00177267a94ca820ecf4e80093e390753568b7d8cb3c1a (from https://pypi.org/simple/protobuf/))
52Reason for being yanked: This version claims to support Python 2 but does not
53 ERROR: Command errored out with exit status 1:
54 command: 'C:\Users\alaiy\.local\pipx\venvs\eth-brownie\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\alaiy\\AppData\\Local\\Temp\\pip-install-d1bskwa2\\cytoolz_f765f335272241adba2138f1920a35cd\\setup.py'"'"'; __file__='"'"'C:\\Users\\alaiy\\AppData\\Local\\Temp\\pip-install-d1bskwa2\\cytoolz_f765f335272241adba2138f1920a35cd\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\alaiy\AppData\Local\Temp\pip-wheel-pxzumeav'
55 cwd: C:\Users\alaiy\AppData\Local\Temp\pip-install-d1bskwa2\cytoolz_f765f335272241adba2138f1920a35cd\
56 Complete output (70 lines):
57 ALERT: Cython not installed. Building without Cython.
58 running bdist_wheel
59 running build
60 running build_py
61 creating build
62 creating build\lib.win-amd64-3.10
63 creating build\lib.win-amd64-3.10\cytoolz
64 copying cytoolz\compatibility.py -> build\lib.win-amd64-3.10\cytoolz
65 copying cytoolz\utils_test.py -> build\lib.win-amd64-3.10\cytoolz
66
Any help would be appreciated!
Edit: Found a solution. Cython appears to not be supported on Python 3.10 (ref https://github.com/eth-brownie/brownie/issues/1300 and https://github.com/cython/cython/issues/4046). I downgraded to Python 3.9.7 and eth-brownie installation worked!)
ANSWER
Answered 2022-Jan-02 at 09:59I used pip install eth-brownie and it worked fine, I didnt need to downgrade. Im new to this maybe I could be wrong but it worked fine with me.
QUESTION
IntelliJ - Invalid source release: 17
Asked 2022-Mar-17 at 13:46I've created a new Java project in IntelliJ with Gradle that uses Java 17. When running my app it has the error Cause: error: invalid source release: 17
.
My Settings
I've installed openjdk-17
through IntelliJ
and set it as my Project SDK
.
The Project language level
has been set to 17 - Sealed types, always-strict floating-point semantics
.
In Modules -> Sources
I've set the Language level
to Project default (17 - Sealed types, always strict floating-point semantics)
.
In Modules -> Dependencies
I've set the Module SDK
to Project SDK openjdk-17
.
In Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler
I've set the Project bytecode version
to 17
.
Gradle
1plugins {
2 id 'org.springframework.boot' version '2.5.6'
3 id 'io.spring.dependency-management' version '1.0.11.RELEASE'
4 id 'java'
5}
6
7group = 'com.app'
8version = '0.0.1-SNAPSHOT'
9sourceCompatibility = '17'
10
11repositories {
12 mavenCentral()
13}
14
15dependencies {
16 implementation 'org.springframework.boot:spring-boot-starter-web'
17 implementation 'org.springframework.boot:spring-boot-starter-websocket'
18 testImplementation 'org.springframework.boot:spring-boot-starter-test'
19 implementation 'com.fasterxml.jackson.core:jackson-core:2.13.0'
20 implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
21}
22
23test {
24 useJUnitPlatform()
25}
26
I've looked at all of the answers here but I can't seem to fix this. I must be missing something but I can't find it. I've not had any problems using Java 8 or 11.
How do I resolve this?
ANSWER
Answered 2021-Oct-24 at 14:23The message typically entails that your JAVA_HOME environment variable points to a different Java version.
Here are the steps to follow:
- Close IntelliJ IDEA
- Open a terminal window and check your JAVA_HOME variable value:
- *nix system:
echo $JAVA_HOME
- Windows system:
echo %JAVA_HOME%
- *nix system:
- The JAVA_HOME path should be pointing to a different path, then set it to the openjdk-17 path:
- *nix system:
export JAVA_HOME=/path/to/openjdk-17
- Windows system:
set JAVA_HOME=path\to\openjdk-17
- *nix system:
- Open your project again in IntelliJ IDEA
- Make sure to set both source and target compatibility versions (not only the
sourceCompatibility
)
You should be able to build your project.
EDIT: Gradle ToolchainYou may need also to instruct Gradle to use a different JVM than the one it uses itself by setting the Java plugin toolchain to your target version:
1plugins {
2 id 'org.springframework.boot' version '2.5.6'
3 id 'io.spring.dependency-management' version '1.0.11.RELEASE'
4 id 'java'
5}
6
7group = 'com.app'
8version = '0.0.1-SNAPSHOT'
9sourceCompatibility = '17'
10
11repositories {
12 mavenCentral()
13}
14
15dependencies {
16 implementation 'org.springframework.boot:spring-boot-starter-web'
17 implementation 'org.springframework.boot:spring-boot-starter-websocket'
18 testImplementation 'org.springframework.boot:spring-boot-starter-test'
19 implementation 'com.fasterxml.jackson.core:jackson-core:2.13.0'
20 implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
21}
22
23test {
24 useJUnitPlatform()
25}
26// build.gradle
27java {
28 toolchain {
29 languageVersion = JavaLanguageVersion.of(17)
30 }
31}
32
QUESTION
NestJS GraphQL subscriptions not working with `graphql-ws`
Asked 2022-Feb-21 at 12:01I'm trying to upgrade our NestJS GraphQL subscriptions server to utilize graphql-ws
rather than the current subscriptions-transport-ws
(as suggested by the NestJS documentation).
I upgraded the NestJS version to
1 "@nestjs/core": "^8.0.6",
2 "@nestjs/graphql": "^9.0.4",
3 "@nestjs/platform-express": "^8.0.6",
4 "graphql": "^15.5.3",
5 "graphql-tools": "^8.2.0",
6 "apollo-server-express": "^3.3.0",
7
And after, I added the subscriptions
option to the App.Module
:
1 "@nestjs/core": "^8.0.6",
2 "@nestjs/graphql": "^9.0.4",
3 "@nestjs/platform-express": "^8.0.6",
4 "graphql": "^15.5.3",
5 "graphql-tools": "^8.2.0",
6 "apollo-server-express": "^3.3.0",
7 GraphQLModule.forRoot({
8 autoSchemaFile: true,
9 sortSchema: true,
10 playground: true,
11 installSubscriptionHandlers: true,
12 subscriptions: {
13 'graphql-ws': true
14 },
15 }),
16
However when I subscribe (in playground) to a previously working subscription, I get:
1 "@nestjs/core": "^8.0.6",
2 "@nestjs/graphql": "^9.0.4",
3 "@nestjs/platform-express": "^8.0.6",
4 "graphql": "^15.5.3",
5 "graphql-tools": "^8.2.0",
6 "apollo-server-express": "^3.3.0",
7 GraphQLModule.forRoot({
8 autoSchemaFile: true,
9 sortSchema: true,
10 playground: true,
11 installSubscriptionHandlers: true,
12 subscriptions: {
13 'graphql-ws': true
14 },
15 }),
16{
17 "error": "Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct."
18}
19
And in the console I get:
1 "@nestjs/core": "^8.0.6",
2 "@nestjs/graphql": "^9.0.4",
3 "@nestjs/platform-express": "^8.0.6",
4 "graphql": "^15.5.3",
5 "graphql-tools": "^8.2.0",
6 "apollo-server-express": "^3.3.0",
7 GraphQLModule.forRoot({
8 autoSchemaFile: true,
9 sortSchema: true,
10 playground: true,
11 installSubscriptionHandlers: true,
12 subscriptions: {
13 'graphql-ws': true
14 },
15 }),
16{
17 "error": "Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct."
18}
19WebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol "graphql-ws" requested by the client. graphql-ws implements exclusively the "graphql-transport-ws" subprotocol, please make sure that the client implements it too.
20
Things I have tried:
- Adding the
graphql-ws
package - Upgrading the NestJS version again
- Removing the
installSubscriptionHandlers
option from config - Setting
graphql-ws
configs instead of passingtrue
- Using the
WebSocket Test Client
Google Chrome extension instead of Playground
But none have worked. Sorry for the long post. How can I fix this?
ANSWER
Answered 2021-Sep-16 at 13:35At the time of release of Apollo Server 3, the protocol used in the graphql-ws library is not yet supported by GraphQL Playground or Apollo Explorer.
see here
It's only advisable to use graphql-ws if interacting with subscriptions via playground is not of much use to you and you're okay interacting with subscriptions solely from your own client that has been setup to use graphql-ws.
To setup your client to use graphql-ws with Apollo. see here.
QUESTION
WebSocket not working when trying to send generated answer by keras
Asked 2022-Feb-17 at 12:52I am implementing a simple chatbot using keras and WebSockets. I now have a model that can make a prediction about the user input and send the according answer.
When I do it through command line it works fine, however when I try to send the answer through my WebSocket, the WebSocket doesn't even start anymore.
Here is my working WebSocket code:
1@sock.route('/api')
2def echo(sock):
3 while True:
4 # get user input from browser
5 user_input = sock.receive()
6 # print user input on console
7 print(user_input)
8 # read answer from console
9 response = input()
10 # send response to browser
11 sock.send(response)
12
Here is my code to communicate with the keras model on command line:
1@sock.route('/api')
2def echo(sock):
3 while True:
4 # get user input from browser
5 user_input = sock.receive()
6 # print user input on console
7 print(user_input)
8 # read answer from console
9 response = input()
10 # send response to browser
11 sock.send(response)
12while True:
13 question = input("")
14 ints = predict(question)
15 answer = response(ints, json_data)
16 print(answer)
17
Used methods are those:
1@sock.route('/api')
2def echo(sock):
3 while True:
4 # get user input from browser
5 user_input = sock.receive()
6 # print user input on console
7 print(user_input)
8 # read answer from console
9 response = input()
10 # send response to browser
11 sock.send(response)
12while True:
13 question = input("")
14 ints = predict(question)
15 answer = response(ints, json_data)
16 print(answer)
17def predict(sentence):
18 bag_of_words = convert_sentence_in_bag_of_words(sentence)
19 # pass bag as list and get index 0
20 prediction = model.predict(np.array([bag_of_words]))[0]
21 ERROR_THRESHOLD = 0.25
22 accepted_results = [[tag, probability] for tag, probability in enumerate(prediction) if probability > ERROR_THRESHOLD]
23
24 accepted_results.sort(key=lambda x: x[1], reverse=True)
25
26 output = []
27 for accepted_result in accepted_results:
28 output.append({'intent': classes[accepted_result[0]], 'probability': str(accepted_result[1])})
29 print(output)
30 return output
31
32
33def response(intents, json):
34 tag = intents[0]['intent']
35 intents_as_list = json['intents']
36 for i in intents_as_list:
37 if i['tag'] == tag:
38 res = random.choice(i['responses'])
39 break
40 return res
41
So when I start the WebSocket with the working code I get this output:
1@sock.route('/api')
2def echo(sock):
3 while True:
4 # get user input from browser
5 user_input = sock.receive()
6 # print user input on console
7 print(user_input)
8 # read answer from console
9 response = input()
10 # send response to browser
11 sock.send(response)
12while True:
13 question = input("")
14 ints = predict(question)
15 answer = response(ints, json_data)
16 print(answer)
17def predict(sentence):
18 bag_of_words = convert_sentence_in_bag_of_words(sentence)
19 # pass bag as list and get index 0
20 prediction = model.predict(np.array([bag_of_words]))[0]
21 ERROR_THRESHOLD = 0.25
22 accepted_results = [[tag, probability] for tag, probability in enumerate(prediction) if probability > ERROR_THRESHOLD]
23
24 accepted_results.sort(key=lambda x: x[1], reverse=True)
25
26 output = []
27 for accepted_result in accepted_results:
28 output.append({'intent': classes[accepted_result[0]], 'probability': str(accepted_result[1])})
29 print(output)
30 return output
31
32
33def response(intents, json):
34 tag = intents[0]['intent']
35 intents_as_list = json['intents']
36 for i in intents_as_list:
37 if i['tag'] == tag:
38 res = random.choice(i['responses'])
39 break
40 return res
41 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
42 * Restarting with stat
43 * Serving Flask app 'server' (lazy loading)
44 * Environment: production
45 WARNING: This is a development server. Do not use it in a production deployment.
46 Use a production WSGI server instead.
47 * Debug mode: on
48
But as soon as I have anything of my model in the server.py
class I get this output:
1@sock.route('/api')
2def echo(sock):
3 while True:
4 # get user input from browser
5 user_input = sock.receive()
6 # print user input on console
7 print(user_input)
8 # read answer from console
9 response = input()
10 # send response to browser
11 sock.send(response)
12while True:
13 question = input("")
14 ints = predict(question)
15 answer = response(ints, json_data)
16 print(answer)
17def predict(sentence):
18 bag_of_words = convert_sentence_in_bag_of_words(sentence)
19 # pass bag as list and get index 0
20 prediction = model.predict(np.array([bag_of_words]))[0]
21 ERROR_THRESHOLD = 0.25
22 accepted_results = [[tag, probability] for tag, probability in enumerate(prediction) if probability > ERROR_THRESHOLD]
23
24 accepted_results.sort(key=lambda x: x[1], reverse=True)
25
26 output = []
27 for accepted_result in accepted_results:
28 output.append({'intent': classes[accepted_result[0]], 'probability': str(accepted_result[1])})
29 print(output)
30 return output
31
32
33def response(intents, json):
34 tag = intents[0]['intent']
35 intents_as_list = json['intents']
36 for i in intents_as_list:
37 if i['tag'] == tag:
38 res = random.choice(i['responses'])
39 break
40 return res
41 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
42 * Restarting with stat
43 * Serving Flask app 'server' (lazy loading)
44 * Environment: production
45 WARNING: This is a development server. Do not use it in a production deployment.
46 Use a production WSGI server instead.
47 * Debug mode: on
482022-02-13 11:31:38.887640: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:305] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
492022-02-13 11:31:38.887734: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:271] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
50Metal device set to: Apple M1
51
52systemMemory: 16.00 GB
53maxCacheSize: 5.33 GB
54
It is enough when I just have an import at the top like this: from chatty import response, predict
- even though they are unused.
ANSWER
Answered 2022-Feb-16 at 19:53There is no problem with your websocket route. Could you please share how you are triggering this route? Websocket is a different protocol and I'm suspecting that you are using a HTTP client to test websocket. For example in Postman:
HTTP requests are different than websocket requests. So, you should use appropriate client to test websocket.
QUESTION
Prevent unauthorized http requests redirected to /error from setting session cookie - spring boot - spring security
Asked 2022-Jan-25 at 09:29I'm having some trouble with my application. We're using Spring Boot 2.4.10 and Spring Security 5.4.8. We use cookies to interact with the app.
We have a frontend application stored in src/main/resources
that, among other things, connects to a websocket endpoint exposed in /api/v1/notification
.
application.properties
file:
1# cookie-related settings
2server.servlet.session.cookie.name=mySessionCookie
3server.servlet.session.cookie.path=/
4server.servlet.session.cookie.http-only=true
5server.servlet.session.cookie.secure=true
6
1# cookie-related settings
2server.servlet.session.cookie.name=mySessionCookie
3server.servlet.session.cookie.path=/
4server.servlet.session.cookie.http-only=true
5server.servlet.session.cookie.secure=true
6
7@Configuration
8@EnableWebSecurity
9public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
10 private final String[] authorizedWithoutAuth = {
11 "/",
12 "/index.html",
13 "/static/**"
14 };
15
16 @Override
17 protected void configure(HttpSecurity http) throws Exception {
18 http.httpBasic()
19 .and()
20 .authorizeRequests()
21 .antMatchers(authorizedWithoutAuth).permitAll()
22 .anyRequest().authenticated()
23 .and()
24 .csrf().disable()
25 .and()
26 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
27 .deleteCookies("mySessionCookie");
28 }
29}
30
While no user is logged in, the frontend tries to reach periodically the websocket endpoint to open a connection.
The first api/v1/notification
ends redirected to the /error
endpoint, which returns an HttpServletResponse
with a 'Set-Cookie' header (I think this may be an anonymous cookie set in the first request?) and a 401 status. I cannot change this behaviour.
The following requests to api/v1/notification
use this cookie in the header (while user is not logged in). These requests are also redirected to the /error
endpoint, which returns each time an HttpServletResponse
with 401 status but here, no 'Set-Cookie' header is included.
Once the user logs in with Authorization headers, a correct cookie is set by the response and used in the following requests.
The thing is, sometimes the set cookie suddenly changes again to an invalid one, and the following requests, done with this new invalid cookie, turn into a redirection to the login page.
After checking the code, it seems there is an old api/v1/notification
request (previous to the login request) taking place, with an invalid cookie (the anonymous one, present before login).
This request is redirected to the /error
endpoint: here, once again the HttpServletResponse
has 401 status and is containing a Set-Cookie header that is modifying the browser cookie (replacing the good one).
Following is a scheme of the problem, to hopefully make it easier to understand.
Expected behaviourI would like to prevent an unauthorized request from setting the session cookie.
It's ok if a previous request responds with a 401 code, but I don't want it to change the current set cookie.
I tried...I tried extending the
ErrorController
by returning aResponseEntity
with all the headers present in the inputHttpServletResponse
except for the 'Set-Cookie' header. This doesn't work.I also tried modifying my configuration to disable anonymous requests:
1# cookie-related settings
2server.servlet.session.cookie.name=mySessionCookie
3server.servlet.session.cookie.path=/
4server.servlet.session.cookie.http-only=true
5server.servlet.session.cookie.secure=true
6
7@Configuration
8@EnableWebSecurity
9public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
10 private final String[] authorizedWithoutAuth = {
11 "/",
12 "/index.html",
13 "/static/**"
14 };
15
16 @Override
17 protected void configure(HttpSecurity http) throws Exception {
18 http.httpBasic()
19 .and()
20 .authorizeRequests()
21 .antMatchers(authorizedWithoutAuth).permitAll()
22 .anyRequest().authenticated()
23 .and()
24 .csrf().disable()
25 .and()
26 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
27 .deleteCookies("mySessionCookie");
28 }
29}
30@Configuration
31@EnableWebSecurity
32public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
33 private final String[] authorizedWithoutAuth = {
34 "/",
35 "/index.html",
36 "/static/**"
37 };
38
39 @Override
40 protected void configure(HttpSecurity http) throws Exception {
41 http.httpBasic()
42 .and()
43 .anonymous().disable()
44 .authorizeRequests()
45 // .antMatchers(authorizedWithoutAuth).permitAll() I had to remove these from here, and include them in the method below
46 .anyRequest().authenticated()
47 .and()
48 .csrf().disable()
49 .and()
50 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
51 .deleteCookies("mySessionCookie");
52 }
53
54 @Override
55 public void configure(WebSecurity web) throws Exception {
56 web.ignoring().antMatchers(authorizedWithoutAuth);
57 }
58}
59
but the session cookie is still set this way too, with 401 requests.
I also tried using @ControllerAdvice
to handle the exceptions, but these are thrown by Spring Security in the AbstractSecurityInterceptor
, as learnt in this response.
Thak you all for your time. Sorry for the post length :)
ANSWER
Answered 2022-Jan-25 at 09:29I started digging in Spring Security libraries, and noticed the session cookie was being set in HttpSessionRequestCache.saveRequest(...)
method:
1# cookie-related settings
2server.servlet.session.cookie.name=mySessionCookie
3server.servlet.session.cookie.path=/
4server.servlet.session.cookie.http-only=true
5server.servlet.session.cookie.secure=true
6
7@Configuration
8@EnableWebSecurity
9public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
10 private final String[] authorizedWithoutAuth = {
11 "/",
12 "/index.html",
13 "/static/**"
14 };
15
16 @Override
17 protected void configure(HttpSecurity http) throws Exception {
18 http.httpBasic()
19 .and()
20 .authorizeRequests()
21 .antMatchers(authorizedWithoutAuth).permitAll()
22 .anyRequest().authenticated()
23 .and()
24 .csrf().disable()
25 .and()
26 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
27 .deleteCookies("mySessionCookie");
28 }
29}
30@Configuration
31@EnableWebSecurity
32public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
33 private final String[] authorizedWithoutAuth = {
34 "/",
35 "/index.html",
36 "/static/**"
37 };
38
39 @Override
40 protected void configure(HttpSecurity http) throws Exception {
41 http.httpBasic()
42 .and()
43 .anonymous().disable()
44 .authorizeRequests()
45 // .antMatchers(authorizedWithoutAuth).permitAll() I had to remove these from here, and include them in the method below
46 .anyRequest().authenticated()
47 .and()
48 .csrf().disable()
49 .and()
50 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
51 .deleteCookies("mySessionCookie");
52 }
53
54 @Override
55 public void configure(WebSecurity web) throws Exception {
56 web.ignoring().antMatchers(authorizedWithoutAuth);
57 }
58}
59public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
60 if (!this.requestMatcher.matches(request)) {
61 if (this.logger.isTraceEnabled()) {
62 this.logger.trace(LogMessage.format("Did not save request since it did not match [%s]", this.requestMatcher));
63 }
64 } else {
65 DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, this.portResolver);
66 if (!this.createSessionAllowed && request.getSession(false) == null) {
67 this.logger.trace("Did not save request since there's no session and createSessionAllowed is false");
68 } else {
69 request.getSession().setAttribute(this.sessionAttrName, savedRequest);
70 if (this.logger.isDebugEnabled()) {
71 this.logger.debug(LogMessage.format("Saved request %s to session", savedRequest.getRedirectUrl()));
72 }
73 }
74 }
75}
76
The 'Set-Cookie' header appears when creating the DefaultSavedRequest
object.
I changed my WebSecurityConfig
to the following:
1# cookie-related settings
2server.servlet.session.cookie.name=mySessionCookie
3server.servlet.session.cookie.path=/
4server.servlet.session.cookie.http-only=true
5server.servlet.session.cookie.secure=true
6
7@Configuration
8@EnableWebSecurity
9public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
10 private final String[] authorizedWithoutAuth = {
11 "/",
12 "/index.html",
13 "/static/**"
14 };
15
16 @Override
17 protected void configure(HttpSecurity http) throws Exception {
18 http.httpBasic()
19 .and()
20 .authorizeRequests()
21 .antMatchers(authorizedWithoutAuth).permitAll()
22 .anyRequest().authenticated()
23 .and()
24 .csrf().disable()
25 .and()
26 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
27 .deleteCookies("mySessionCookie");
28 }
29}
30@Configuration
31@EnableWebSecurity
32public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
33 private final String[] authorizedWithoutAuth = {
34 "/",
35 "/index.html",
36 "/static/**"
37 };
38
39 @Override
40 protected void configure(HttpSecurity http) throws Exception {
41 http.httpBasic()
42 .and()
43 .anonymous().disable()
44 .authorizeRequests()
45 // .antMatchers(authorizedWithoutAuth).permitAll() I had to remove these from here, and include them in the method below
46 .anyRequest().authenticated()
47 .and()
48 .csrf().disable()
49 .and()
50 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
51 .deleteCookies("mySessionCookie");
52 }
53
54 @Override
55 public void configure(WebSecurity web) throws Exception {
56 web.ignoring().antMatchers(authorizedWithoutAuth);
57 }
58}
59public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
60 if (!this.requestMatcher.matches(request)) {
61 if (this.logger.isTraceEnabled()) {
62 this.logger.trace(LogMessage.format("Did not save request since it did not match [%s]", this.requestMatcher));
63 }
64 } else {
65 DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, this.portResolver);
66 if (!this.createSessionAllowed && request.getSession(false) == null) {
67 this.logger.trace("Did not save request since there's no session and createSessionAllowed is false");
68 } else {
69 request.getSession().setAttribute(this.sessionAttrName, savedRequest);
70 if (this.logger.isDebugEnabled()) {
71 this.logger.debug(LogMessage.format("Saved request %s to session", savedRequest.getRedirectUrl()));
72 }
73 }
74 }
75}
76@Configuration
77@EnableWebSecurity
78public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
79 ...
80
81 @Override
82 protected void configure(HttpSecurity http) throws Exception {
83 http.httpBasic()
84 .and()
85 .requestCache().requestCache(getHttpSessionRequestCache()) // This is new
86 .and()
87 .authorizeRequests().antMatchers(authorizedWithoutAuth).permitAll()
88 .anyRequest().authenticated()
89 .and()
90 .csrf().disable()
91 .and()
92 .logout().logoutUrl("/api/v1/logout").invalidateHttpSession(true)
93 .deleteCookies("mySessionCookie");
94 }
95
96
97 public HttpSessionRequestCache getHttpSessionRequestCache()
98 {
99 HttpSessionRequestCache httpSessionRequestCache = new HttpSessionRequestCache();
100 httpSessionRequestCache.setCreateSessionAllowed(false); // I modified this parameter
101 return httpSessionRequestCache;
102 }
103}
104
and now it works. When logging in with Authorization headers, the cookie is being set correctly, but all the requests with an invalid session cookie or an expired one return a 401
response without setting a new one.
Also, after reading this answer, I understood better what this createSessionAllowed
was doing
QUESTION
How to give certificate to Java Websocket?
Asked 2022-Jan-20 at 10:33Forgive me for the newb question, but I am confused and obviously not understanding the fundamentals or explanations of how to use a Websocket server hosted over HTTPS
. Everything I find online leads me to have more questions than answers.
I have a Websocket server hosted on my HTTPS
website using Java code.
This is my WebsocketServer.java
file:
1import org.java_websocket.WebSocket;
2import org.java_websocket.handshake.ClientHandshake;
3import org.java_websocket.server.WebSocketServer;
4
5import java.net.InetSocketAddress;
6import java.util.HashSet;
7import java.util.Set;
8
9import org.apache.logging.log4j.LogManager;
10import org.apache.logging.log4j.Logger;
11
12public class WebsocketServer extends WebSocketServer {
13
14 private static final Logger logger = LogManager.getLogger(WebsocketServer.class);
15
16 private static int TCP_PORT = 6868;
17
18 private static Set<WebSocket> conns;
19
20 public WebsocketServer() {
21 super(new InetSocketAddress(TCP_PORT));
22 conns = new HashSet<>();
23 }
24
25 @Override
26 public void onOpen(WebSocket conn, ClientHandshake handshake) {
27 conns.add(conn);
28 logger.info("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
29 logger.info("Size of connection list: " + conns.size());
30 }
31
32 @Override
33 public void onClose(WebSocket conn, int code, String reason, boolean remote) {
34 conns.remove(conn);
35 logger.info("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
36 }
37
38 @Override
39 public void onMessage(WebSocket conn, String message) {
40 logger.info("Message from client: {}", message);
41 // for (WebSocket sock : conns) {
42 // sock.send("SENDING BACK" + message);
43 // }
44 }
45
46 @Override
47 public void onError(WebSocket conn, Exception ex) {
48
49 // ex.printStackTrace();
50 try {
51 if (conn != null) {
52 conns.remove(conn);
53 // do some thing if required
54 }
55 logger.info("ERROR from {}", conn.getRemoteSocketAddress().getAddress().getHostAddress());
56 } catch (Exception e) {
57 logger.info("onError: WebSocketServer may already be running");
58
59 }
60
61 }
62
63 public Set<WebSocket> getConns() {
64 return conns;
65 }
66
67}
68
69
Then I started the WebsocketServer
like this:
1import org.java_websocket.WebSocket;
2import org.java_websocket.handshake.ClientHandshake;
3import org.java_websocket.server.WebSocketServer;
4
5import java.net.InetSocketAddress;
6import java.util.HashSet;
7import java.util.Set;
8
9import org.apache.logging.log4j.LogManager;
10import org.apache.logging.log4j.Logger;
11
12public class WebsocketServer extends WebSocketServer {
13
14 private static final Logger logger = LogManager.getLogger(WebsocketServer.class);
15
16 private static int TCP_PORT = 6868;
17
18 private static Set<WebSocket> conns;
19
20 public WebsocketServer() {
21 super(new InetSocketAddress(TCP_PORT));
22 conns = new HashSet<>();
23 }
24
25 @Override
26 public void onOpen(WebSocket conn, ClientHandshake handshake) {
27 conns.add(conn);
28 logger.info("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
29 logger.info("Size of connection list: " + conns.size());
30 }
31
32 @Override
33 public void onClose(WebSocket conn, int code, String reason, boolean remote) {
34 conns.remove(conn);
35 logger.info("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
36 }
37
38 @Override
39 public void onMessage(WebSocket conn, String message) {
40 logger.info("Message from client: {}", message);
41 // for (WebSocket sock : conns) {
42 // sock.send("SENDING BACK" + message);
43 // }
44 }
45
46 @Override
47 public void onError(WebSocket conn, Exception ex) {
48
49 // ex.printStackTrace();
50 try {
51 if (conn != null) {
52 conns.remove(conn);
53 // do some thing if required
54 }
55 logger.info("ERROR from {}", conn.getRemoteSocketAddress().getAddress().getHostAddress());
56 } catch (Exception e) {
57 logger.info("onError: WebSocketServer may already be running");
58
59 }
60
61 }
62
63 public Set<WebSocket> getConns() {
64 return conns;
65 }
66
67}
68
69WebsocketServer websocketServer;
70// Start socket server
71websocketServer = new WebsocketServer();
72websocketServer.start();
73
And on the client side, I connect to it like this:
1import org.java_websocket.WebSocket;
2import org.java_websocket.handshake.ClientHandshake;
3import org.java_websocket.server.WebSocketServer;
4
5import java.net.InetSocketAddress;
6import java.util.HashSet;
7import java.util.Set;
8
9import org.apache.logging.log4j.LogManager;
10import org.apache.logging.log4j.Logger;
11
12public class WebsocketServer extends WebSocketServer {
13
14 private static final Logger logger = LogManager.getLogger(WebsocketServer.class);
15
16 private static int TCP_PORT = 6868;
17
18 private static Set<WebSocket> conns;
19
20 public WebsocketServer() {
21 super(new InetSocketAddress(TCP_PORT));
22 conns = new HashSet<>();
23 }
24
25 @Override
26 public void onOpen(WebSocket conn, ClientHandshake handshake) {
27 conns.add(conn);
28 logger.info("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
29 logger.info("Size of connection list: " + conns.size());
30 }
31
32 @Override
33 public void onClose(WebSocket conn, int code, String reason, boolean remote) {
34 conns.remove(conn);
35 logger.info("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
36 }
37
38 @Override
39 public void onMessage(WebSocket conn, String message) {
40 logger.info("Message from client: {}", message);
41 // for (WebSocket sock : conns) {
42 // sock.send("SENDING BACK" + message);
43 // }
44 }
45
46 @Override
47 public void onError(WebSocket conn, Exception ex) {
48
49 // ex.printStackTrace();
50 try {
51 if (conn != null) {
52 conns.remove(conn);
53 // do some thing if required
54 }
55 logger.info("ERROR from {}", conn.getRemoteSocketAddress().getAddress().getHostAddress());
56 } catch (Exception e) {
57 logger.info("onError: WebSocketServer may already be running");
58
59 }
60
61 }
62
63 public Set<WebSocket> getConns() {
64 return conns;
65 }
66
67}
68
69WebsocketServer websocketServer;
70// Start socket server
71websocketServer = new WebsocketServer();
72websocketServer.start();
73 // APP_WEB_SOCKET is the url to my site: api.my_custom_domain.com
74 var connection = new WebSocket("wss://" + APP_WEB_SOCKET + ":6868");
75
QUESTIONS:
I keep reading that I need a certificate if I want to use wss
over HTTPS
, but cannot find any documents that explain what this means in a way that I can understand.
My app is hosted in AWS Elastic Beanstalk environment. Do I need to somehow add a certificate to the setup of the WebsocketServer
in my Java code?
Example:
1import org.java_websocket.WebSocket;
2import org.java_websocket.handshake.ClientHandshake;
3import org.java_websocket.server.WebSocketServer;
4
5import java.net.InetSocketAddress;
6import java.util.HashSet;
7import java.util.Set;
8
9import org.apache.logging.log4j.LogManager;
10import org.apache.logging.log4j.Logger;
11
12public class WebsocketServer extends WebSocketServer {
13
14 private static final Logger logger = LogManager.getLogger(WebsocketServer.class);
15
16 private static int TCP_PORT = 6868;
17
18 private static Set<WebSocket> conns;
19
20 public WebsocketServer() {
21 super(new InetSocketAddress(TCP_PORT));
22 conns = new HashSet<>();
23 }
24
25 @Override
26 public void onOpen(WebSocket conn, ClientHandshake handshake) {
27 conns.add(conn);
28 logger.info("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
29 logger.info("Size of connection list: " + conns.size());
30 }
31
32 @Override
33 public void onClose(WebSocket conn, int code, String reason, boolean remote) {
34 conns.remove(conn);
35 logger.info("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
36 }
37
38 @Override
39 public void onMessage(WebSocket conn, String message) {
40 logger.info("Message from client: {}", message);
41 // for (WebSocket sock : conns) {
42 // sock.send("SENDING BACK" + message);
43 // }
44 }
45
46 @Override
47 public void onError(WebSocket conn, Exception ex) {
48
49 // ex.printStackTrace();
50 try {
51 if (conn != null) {
52 conns.remove(conn);
53 // do some thing if required
54 }
55 logger.info("ERROR from {}", conn.getRemoteSocketAddress().getAddress().getHostAddress());
56 } catch (Exception e) {
57 logger.info("onError: WebSocketServer may already be running");
58
59 }
60
61 }
62
63 public Set<WebSocket> getConns() {
64 return conns;
65 }
66
67}
68
69WebsocketServer websocketServer;
70// Start socket server
71websocketServer = new WebsocketServer();
72websocketServer.start();
73 // APP_WEB_SOCKET is the url to my site: api.my_custom_domain.com
74 var connection = new WebSocket("wss://" + APP_WEB_SOCKET + ":6868");
75WebsocketServer websocketServer;
76// Start socket server
77websocketServer = new WebsocketServer();
78
79// example guessing
80websocketServer.cert = "SOMETHING";??
81websocketServer.start();
82
Does the client code need to be changed at all?
Who needs the certificate?
If someone could please explain what I am missing or point me in the correct direction, I would really appreciate it.
ANSWER
Answered 2022-Jan-13 at 14:50Keep it easy.
Certs inside your application are complex - they are hard to manage and you will get problems to run your application in a modern cloud environment (start new environments, renew certs, scale your application, ...).
Simple conclusion: Dont implement any certs.
How-to get encrypted connections?As Mike already pointed out in the comments: WebSockets are just upgraded HTTP(S) connections. A normal webserver (nginx, apache) takes care about the certs. It can be done in kubernetes (as ingress-controller) or with a "bare-metal" webserver.
Both of them should act as a reverse-proxy. This means: Your java-application doesn't know anything about certs. It has just unencrypted connections - like in your code on port 6868
.
But the client will not use this port. 6868
is only internally reachable.
The client will call your reverse-proxy at the normal HTTPS port (=443). The reverse-proxy will forward the connection to your java-application.
Here some links for further information:
QUESTION
Jenkins with Kubernetes Client Plugin - NoSuchMethodError
Asked 2022-Jan-08 at 09:06After upgrading the jenkins plugin Kubernetes Client to version 1.30.3 (also for 1.31.1) I get the following exceptions in the logs of jenkins when I start a build:
1Timer task org.csanchez.jenkins.plugins.kubernetes.KubernetesClientProvider$UpdateConnectionCount@2c16d367 failed
2java.lang.NoSuchMethodError: 'okhttp3.OkHttpClient io.fabric8.kubernetes.client.HttpClientAware.getHttpClient()'
3 at org.csanchez.jenkins.plugins.kubernetes.KubernetesClientProvider$UpdateConnectionCount.doRun(KubernetesClientProvider.java:150)
4 at hudson.triggers.SafeTimerTask.run(SafeTimerTask.java:90)
5 at jenkins.security.ImpersonatingScheduledExecutorService$1.run(ImpersonatingScheduledExecutorService.java:67)
6 at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
7 at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
8 at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
9 at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
10 at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
11 at java.base/java.lang.Thread.run(Thread.java:829)
12
After some of these eceptions the build itself is cancelled with this error:
1Timer task org.csanchez.jenkins.plugins.kubernetes.KubernetesClientProvider$UpdateConnectionCount@2c16d367 failed
2java.lang.NoSuchMethodError: 'okhttp3.OkHttpClient io.fabric8.kubernetes.client.HttpClientAware.getHttpClient()'
3 at org.csanchez.jenkins.plugins.kubernetes.KubernetesClientProvider$UpdateConnectionCount.doRun(KubernetesClientProvider.java:150)
4 at hudson.triggers.SafeTimerTask.run(SafeTimerTask.java:90)
5 at jenkins.security.ImpersonatingScheduledExecutorService$1.run(ImpersonatingScheduledExecutorService.java:67)
6 at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
7 at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
8 at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
9 at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
10 at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
11 at java.base/java.lang.Thread.run(Thread.java:829)
12java.io.IOException: Timed out waiting for websocket connection. You should increase the value of system property org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator.websocketConnectionTimeout currently set at 30 seconds
13at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.doLaunch(ContainerExecDecorator.java:451)
14at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.launch(ContainerExecDecorator.java:338)
15at hudson.Launcher$ProcStarter.start(Launcher.java:507)
16at org.jenkinsci.plugins.durabletask.BourneShellScript.launchWithCookie(BourneShellScript.java:176)
17at org.jenkinsci.plugins.durabletask.FileMonitoringTask.launch(FileMonitoringTask.java:132)
18at org.jenkinsci.plugins.workflow.steps.durable_task.DurableTaskStep$Execution.start(DurableTaskStep.java:324)
19at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:319)
20
Do you have an idea what can be done?
ANSWER
Answered 2022-Jan-05 at 11:55Downgrade the plugin to kubernetes-client-api:5.10.1-171.vaa0774fb8c20. The latest one has the compatibility issue as of now.
new info: The issue is now solved with upgrading the Kubernetes plugin to version: 1.31.2 https://issues.jenkins.io/browse/JENKINS-67483
QUESTION
Activiti 6.0.0 UI app / in-memory H2 database in tomcat9 / java version "9.0.1"
Asked 2021-Dec-16 at 09:41I just downloaded activiti-app from github.com/Activiti/Activiti/releases/download/activiti-6.0.0/…
and deployed in tomcat9, but I have this errors when init the app:
1 11:29:40,090 [http-nio-8080-exec-8] INFO org.activiti.app.conf.AsyncConfiguration - Creating Async Task Executor
211:29:40,887 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring Datasource
311:29:40,910 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring Datasource with following properties (omitted password for security)
411:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource driver: org.h2.Driver
511:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource url : jdbc:h2:mem:activiti;DB_CLOSE_DELAY=-1
611:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource user name : sa
711:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Min pool size | Max pool size | acquire increment : 10 | 100 | 5
811:29:40,947 [http-nio-8080-exec-8] INFO com.mchange.v2.log.MLog - MLog clients using log4j logging.
911:29:41,014 [http-nio-8080-exec-8] INFO com.mchange.v2.c3p0.C3P0Registry - Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
1011:29:41,290 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring EntityManager
1111:29:42,220 [http-nio-8080-exec-8] INFO com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0wdal156qsqtw1cxe|70e1a94b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> org.h2.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0wdal156qsqtw1cxe|70e1a94b, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:h2:mem:activiti;DB_CLOSE_DELAY=-1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 1800, maxIdleTimeExcessConnections -> 1800, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {password=******, user=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> true, testConnectionOnCheckout -> true, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
1211:29:43,183 [http-nio-8080-exec-8] ERROR org.activiti.app.conf.SecurityConfiguration - Could not configure authentication mechanism:
13org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbAuthenticationProvider' defined in class path resource [org/activiti/app/conf/SecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationProvider]: Circular reference involving containing bean 'securityConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dbAuthenticationProvider' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.activiti.app.service.api.UserCache org.activiti.app.security.UserDetailsService.userCache; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userCacheImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.activiti.engine.IdentityService org.activiti.app.service.idm.UserCacheImpl.identityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'activitiEngineConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.transaction.PlatformTransactionManager org.activiti.app.conf.ActivitiEngineConfiguration.transactionManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'annotationDrivenTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
14 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
15 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
16 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
17 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
18 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
19 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
20 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
21 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
22 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
23 at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:322)
24 at org.activiti.app.conf.SecurityConfiguration$$EnhancerBySpringCGLIB$$e6992200.dbAuthenticationProvider(<generated>)
25 at org.activiti.app.conf.SecurityConfiguration.configureGlobal(SecurityConfiguration.java:74)
26 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
27 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
28 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
29 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
30 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:642)
31 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
32 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
33 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
34 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
35 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
36 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
37 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
38 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
39 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
40 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
41 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
42 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
43 at org.activiti.app.servlet.WebConfigurer.contextInitialized(WebConfigurer.java:62)
44 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
45 at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5230)
46 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
47 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
48 at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:698)
49 at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:696)
50 at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1024)
51 at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:544)
52 at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1690)
53 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
54 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
55 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
56 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
57 at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:293)
58 at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
59 at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
60 at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1614)
61 at org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServlet.java:292)
62 at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:210)
63 at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
64 at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
65 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
66 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
67 at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:211)
68 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
69 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
70 at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
71 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
72 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
73 at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126)
74 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
75 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
76 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
77 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
78 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:659)
79 at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:378)
80 at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:56)
81 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
82 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
83 at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
84 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
85 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
86 at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
87 at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
88 at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
89 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
90 at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
91 at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
92 at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
93 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
94 at java.base/java.lang.Thread.run(Thread.java:844)
95Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationProvider]: Circular reference involving containing bean 'securityConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dbAuthenticationProvider' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.activiti.app.service.api.UserCache org.activiti.app.security.UserDetailsService.userCache; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userCacheImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.activiti.engine.IdentityService org.activiti.app.service.idm.UserCacheImpl.identityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'activitiEngineConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.transaction.PlatformTransactionManager org.activiti.app.conf.ActivitiEngineConfiguration.transactionManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'annotationDrivenTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
96 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
97 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
98 ... 80 more
99
and here my activiti-app.properties file:
1 11:29:40,090 [http-nio-8080-exec-8] INFO org.activiti.app.conf.AsyncConfiguration - Creating Async Task Executor
211:29:40,887 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring Datasource
311:29:40,910 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring Datasource with following properties (omitted password for security)
411:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource driver: org.h2.Driver
511:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource url : jdbc:h2:mem:activiti;DB_CLOSE_DELAY=-1
611:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - datasource user name : sa
711:29:40,911 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Min pool size | Max pool size | acquire increment : 10 | 100 | 5
811:29:40,947 [http-nio-8080-exec-8] INFO com.mchange.v2.log.MLog - MLog clients using log4j logging.
911:29:41,014 [http-nio-8080-exec-8] INFO com.mchange.v2.c3p0.C3P0Registry - Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
1011:29:41,290 [http-nio-8080-exec-8] INFO org.activiti.app.conf.DatabaseConfiguration - Configuring EntityManager
1111:29:42,220 [http-nio-8080-exec-8] INFO com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0wdal156qsqtw1cxe|70e1a94b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> org.h2.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0wdal156qsqtw1cxe|70e1a94b, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:h2:mem:activiti;DB_CLOSE_DELAY=-1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 1800, maxIdleTimeExcessConnections -> 1800, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {password=******, user=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> true, testConnectionOnCheckout -> true, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
1211:29:43,183 [http-nio-8080-exec-8] ERROR org.activiti.app.conf.SecurityConfiguration - Could not configure authentication mechanism:
13org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbAuthenticationProvider' defined in class path resource [org/activiti/app/conf/SecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationProvider]: Circular reference involving containing bean 'securityConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dbAuthenticationProvider' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.activiti.app.service.api.UserCache org.activiti.app.security.UserDetailsService.userCache; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userCacheImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.activiti.engine.IdentityService org.activiti.app.service.idm.UserCacheImpl.identityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'activitiEngineConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.transaction.PlatformTransactionManager org.activiti.app.conf.ActivitiEngineConfiguration.transactionManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'annotationDrivenTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
14 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
15 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
16 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
17 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
18 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
19 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
20 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
21 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
22 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
23 at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:322)
24 at org.activiti.app.conf.SecurityConfiguration$$EnhancerBySpringCGLIB$$e6992200.dbAuthenticationProvider(<generated>)
25 at org.activiti.app.conf.SecurityConfiguration.configureGlobal(SecurityConfiguration.java:74)
26 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
27 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
28 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
29 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
30 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:642)
31 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
32 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
33 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
34 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
35 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
36 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
37 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
38 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
39 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
40 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
41 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
42 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
43 at org.activiti.app.servlet.WebConfigurer.contextInitialized(WebConfigurer.java:62)
44 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
45 at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5230)
46 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
47 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
48 at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:698)
49 at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:696)
50 at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1024)
51 at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:544)
52 at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1690)
53 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
54 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
55 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
56 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
57 at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:293)
58 at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
59 at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
60 at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1614)
61 at org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServlet.java:292)
62 at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:210)
63 at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
64 at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
65 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
66 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
67 at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:211)
68 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
69 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
70 at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
71 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
72 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
73 at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126)
74 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
75 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
76 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
77 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
78 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:659)
79 at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:378)
80 at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:56)
81 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
82 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
83 at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
84 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
85 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
86 at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
87 at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
88 at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
89 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
90 at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
91 at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
92 at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
93 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
94 at java.base/java.lang.Thread.run(Thread.java:844)
95Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationProvider]: Circular reference involving containing bean 'securityConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dbAuthenticationProvider' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.activiti.app.service.api.UserCache org.activiti.app.security.UserDetailsService.userCache; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userCacheImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.activiti.engine.IdentityService org.activiti.app.service.idm.UserCacheImpl.identityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'activitiEngineConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.transaction.PlatformTransactionManager org.activiti.app.conf.ActivitiEngineConfiguration.transactionManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'annotationDrivenTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/activiti/app/conf/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
96 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
97 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
98 ... 80 more
99#
100# SECURITY
101#
102security.rememberme.key=testkey
103
104#
105# DATABASE
106#
107
108datasource.driver=org.h2.Driver
109datasource.url=jdbc:h2:mem:activiti;DB_CLOSE_DELAY=-1
110
111#datasource.driver=com.mysql.jdbc.Driver
112#datasource.url=jdbc:mysql://127.0.0.1:3306/activiti6ui?characterEncoding=UTF-8
113
114datasource.username=sa
115datasource.password=
116
117hibernate.dialect=org.hibernate.dialect.H2Dialect
118#hibernate.dialect=org.hibernate.dialect.MySQLDialect
119#hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
120#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
121#hibernate.dialect=org.hibernate.dialect.DB2Dialect
122#hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
123
124#
125# EMAIL
126#
127
128#email.enabled=true
129#email.host=localhost
130#email.port=1025
131#email.useCredentials=false
132#email.username=
133#email.password=
134
135# The base url that will be used to create urls in emails.
136#email.base.url=http://localhost:9999/activiti-app
137
138#email.from.default=no-reply@activiti.alfresco.com
139#email.from.default.name=Activiti
140#email.feedback.default=activiti@alfresco.com
141
142#
143# ACTIVITI
144#
145
146activiti.process-definitions.cache.max=500
147
148#
149# DEFAULT ADMINISTRATOR ACCOUNT
150#
151
152admin.email=admin
153admin.password=test
154admin.lastname=Administrator
155
156admin.group=Superusers
157
158# The maximum file upload limit. Set to -1 to set to 'no limit'. Expressed in bytes
159file.upload.max.size=104857600
160
161# For development purposes, data folder is created inside the sources ./data folder
162contentstorage.fs.rootFolder=data/
163contentstorage.fs.createRoot=true
164contentstorage.fs.depth=4
165contentstorage.fs.blockSize=1024
166
ANSWER
Answered 2021-Dec-16 at 09:41Your title says you are using Java 9. With Activiti 6 you will have to use JDK 1.8 (Java 8).
QUESTION
Split payload from JSON String
Asked 2021-Dec-10 at 22:03I receive these huge Strings via WebSocket:
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5
or
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5[
6 "BTC-31DEC21-36000-C",
7 "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
8]
9
or
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5[
6 "BTC-31DEC21-36000-C",
7 "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
8]
9[
10 "BTC-31DEC21-60000-P",
11 "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
12]
13
I want to check for isMasterFrame
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5[
6 "BTC-31DEC21-36000-C",
7 "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
8]
9[
10 "BTC-31DEC21-60000-P",
11 "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
12]
13let payload = JSON.parse(messageString[1]);
14
15if (payload.hasOwnProperty("isMasterFrame")) {
16 for (let i = 0; i < payload.pairs.length; i++) {
17 let currentPair = payload.data[i]
18 currentPair = currentPair.replace(/\0/g, ''); //Remove null chars
19 if (currentPair.toUpperCase() != 'KILL') {
20 props.onAddAvailablePair(currentPair);
21 }
22 }
23 } else {
24 // print some output with payload which holds "isMasterFrame":false
25 }
26
When I run the code I get error:
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5[
6 "BTC-31DEC21-36000-C",
7 "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
8]
9[
10 "BTC-31DEC21-60000-P",
11 "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
12]
13let payload = JSON.parse(messageString[1]);
14
15if (payload.hasOwnProperty("isMasterFrame")) {
16 for (let i = 0; i < payload.pairs.length; i++) {
17 let currentPair = payload.data[i]
18 currentPair = currentPair.replace(/\0/g, ''); //Remove null chars
19 if (currentPair.toUpperCase() != 'KILL') {
20 props.onAddAvailablePair(currentPair);
21 }
22 }
23 } else {
24 // print some output with payload which holds "isMasterFrame":false
25 }
26TypeError: Cannot read properties of undefined (reading 'length')
27
Data from one inner pair: {\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}
should be split and inserted into the loop one by one
Do you know how I can fix this issue?
ANSWER
Answered 2021-Nov-26 at 02:11You can run the code snippet below to see it in operation. I have also attached a screenshot of a console showing the output of values.
1[
2 "BTC-31DEC21-100000-P",
3 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
4]
5[
6 "BTC-31DEC21-36000-C",
7 "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
8]
9[
10 "BTC-31DEC21-60000-P",
11 "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"
12]
13let payload = JSON.parse(messageString[1]);
14
15if (payload.hasOwnProperty("isMasterFrame")) {
16 for (let i = 0; i < payload.pairs.length; i++) {
17 let currentPair = payload.data[i]
18 currentPair = currentPair.replace(/\0/g, ''); //Remove null chars
19 if (currentPair.toUpperCase() != 'KILL') {
20 props.onAddAvailablePair(currentPair);
21 }
22 }
23 } else {
24 // print some output with payload which holds "isMasterFrame":false
25 }
26TypeError: Cannot read properties of undefined (reading 'length')
27// THIS IS AN ARRAY CONTAINING A JSON
28var messageString = [
29 "BTC-31DEC21-100000-P",
30 "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"
31];
32
33// THE JSON IS AT INDEX '1' OF THE ARRAY SO WE PARSE IT
34let payload = JSON.parse(messageString[1]);
35
36// YOU CAN SEE THE PARSED JSON IN CONSOLE
37console.log(payload.data);
38
39// SINCE isMasterFrame IS EITHER TRUE OR FALSE, WE CAN TEST FOR IT WITHOUT USING hasOwnProperty
40// IF isMasterFrame IS UNDEFINED OR NOT IN THE JSON, THE ELSE BLOCK WILL EXECUTE AND NOT BREAK THE CODE
41if (payload.isMasterFrame) {
42 console.log("1 payload.isMasterFrame: " + payload.isMasterFrame);
43 // SINCE IT IS A JSON, WE HAVE TO LOOP THROUGH THE FIRST PART THIS WAY
44 for (var key in payload.data) {
45 if (payload.data.hasOwnProperty(key)) {
46 console.log("key base: " + key + " -> " + payload.data[key]);
47 // SINCE THE VALUE IS ALSO A JSON OF VALUES, WE LOOP THROUGH AGAIN
48 for (var key_inner1 in payload.data[key]) {
49 if (payload.data[key].hasOwnProperty(key_inner1)) {
50 console.log("key inner1: " + key_inner1 + " -> " + payload.data[key][key_inner1]);
51 // GETTING THE CURRENT PAIR
52 let currentPair = payload.data[key][key_inner1];
53 console.log("CURRENT PAIR");
54 console.log(currentPair);
55 /*
56 currentPair = currentPair.replace(/\0/g, ''); //Remove null chars
57 if (currentPair.toUpperCase() != 'KILL') {
58 props.onAddAvailablePair(currentPair);
59 }
60 */
61
62 // SINCE THE VALUE IS ALSO A JSON OF VALUES, WE LOOP THROUGH AGAIN TO GET THE REAL VALUES
63 for (var key_inner2 in payload.data[key][key_inner1]) {
64 if (payload.data[key][key_inner1].hasOwnProperty(key_inner2)) {
65 // NOW WE CAN DO WHAT WE NEED TO WITH THE ACTUAL VALUES
66 console.log("key inner2: " + key_inner2 + " -> " + payload.data[key][key_inner1][key_inner2]);
67
68 }
69 }
70 }
71 }
72 }
73 }
74
75} else {
76 console.log("2 payload.isMasterFrame: " + payload.isMasterFrame);
77}
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Websocket
Tutorials and Learning Resources are not available at this moment for Websocket