├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── .mvn ├── jvm.config ├── maven.config └── wrapper │ ├── .gitignore │ ├── MavenWrapperDownloader.java │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── release.sh └── src ├── main └── java │ └── com │ └── cosium │ └── matrix_communication_client │ ├── AccessTokenFactory.java │ ├── AccessTokenFactoryFactory.java │ ├── AccessTokensResource.java │ ├── ClientEvent.java │ ├── ClientEventPage.java │ ├── ClientEventResource.java │ ├── CreateRoomInput.java │ ├── CreateRoomOutput.java │ ├── CreatedEvent.java │ ├── HttpClientFactory.java │ ├── JsonBody.java │ ├── JsonHandlers.java │ ├── Lazy.java │ ├── LoginInput.java │ ├── LoginOutput.java │ ├── MatrixApi.java │ ├── MatrixHostname.java │ ├── MatrixResources.java │ ├── MatrixResourcesFactory.java │ ├── MatrixUnprotectedApi.java │ ├── MatrixUri.java │ ├── MatrixUris.java │ ├── Message.java │ ├── RawClientEvent.java │ ├── RawClientEventPage.java │ ├── ResponseInfo.java │ ├── RoomResource.java │ ├── RoomsResource.java │ ├── SimpleAccessTokensResource.java │ ├── SimpleClientEventResource.java │ ├── SimpleMatrixResources.java │ ├── SimpleRoomResource.java │ ├── SimpleRoomsResource.java │ ├── UsernamePasswordAccessTokenFactory.java │ ├── UsernamePasswordAccessTokenFactoryFactory.java │ └── WellKnownMatrixClient.java └── test ├── java └── com │ └── cosium │ └── matrix_communication_client │ ├── AccessTokensResourceTest.java │ ├── LogbackConfigurator.java │ └── RoomResourceTest.java └── resources ├── META-INF └── services │ └── ch.qos.logback.classic.spi.Configurator └── testcontainers.properties /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "maven" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up JDK 17 12 | uses: actions/setup-java@v2 13 | with: 14 | java-version: '17' 15 | distribution: 'adopt' 16 | - name: Build with Maven 17 | run: ./mvnw --batch-mode clean verify 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | 4 | target 5 | .flattened-pom.xml 6 | dependency-reduced-pom.xml 7 | -------------------------------------------------------------------------------- /.mvn/jvm.config: -------------------------------------------------------------------------------- 1 | --add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/java.awt.font=ALL-UNNAMED 2 | -------------------------------------------------------------------------------- /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | --no-snapshot-updates -U -------------------------------------------------------------------------------- /.mvn/wrapper/.gitignore: -------------------------------------------------------------------------------- 1 | maven-wrapper.jar 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Cosium 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/Cosium/matrix-communication-client/actions/workflows/ci.yml/badge.svg)](https://github.com/Cosium/matrix-communication-client/actions/workflows/ci.yml) 2 | [![Maven Central](https://img.shields.io/maven-central/v/com.cosium.matrix_communication_client/matrix-communication-client.svg)](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.cosium.matrix_communication_client%22%20AND%20a%3A%22matrix-communication-client%22) 3 | 4 | 5 | # Matrix Communication Client 6 | 7 | A [Matrix](https://matrix.org/) java client. 8 | 9 | # Example 10 | 11 | ```java 12 | public class Example { 13 | 14 | public static void main(String[] args) { 15 | MatrixResources matrix = 16 | MatrixResources.factory() 17 | .builder() 18 | .https() 19 | .hostname("matrix.example.org") 20 | .defaultPort() 21 | .usernamePassword("jdoe", "secret") 22 | .build(); 23 | 24 | RoomResource room = matrix 25 | .rooms() 26 | .create( 27 | CreateRoomInput.builder() 28 | .name("Science") 29 | .roomAliasName("science") 30 | .topic("Anything about science") 31 | .build()); 32 | 33 | room.sendMessage(Message.builder().body("Hello !").formattedBody("Hello !").build()); 34 | } 35 | } 36 | ``` 37 | 38 | Another example with existing room: 39 | 40 | ```java 41 | public class Example { 42 | 43 | public static void main(String[] args) { 44 | MatrixResources matrix = 45 | MatrixResources.factory() 46 | .builder() 47 | .https() 48 | .hostname("matrix.example.org") 49 | .defaultPort() 50 | .usernamePassword("jdoe", "secret") 51 | .build(); 52 | 53 | RoomResource room = matrix 54 | .rooms() 55 | .byId("!PVvauSmjcHLwoAJkyT:matrix.example.org"); 56 | 57 | room.sendMessage(Message.builder().body("Hello !").formattedBody("Hello !").build()); 58 | } 59 | } 60 | ``` 61 | 62 | # Dependency 63 | 64 | ```xml 65 | 66 | com.cosium.matrix_communication_client 67 | matrix-communication-client 68 | ${matrix-communication-client.version} 69 | 70 | ``` 71 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | com.cosium.maven_oss 5 | maven-oss 6 | 1.5 7 | 8 | com.cosium.matrix_communication_client 9 | matrix-communication-client 10 | 1.10-SNAPSHOT 11 | 12 | 13 | 11 14 | 11 15 | 16 | 2.0.17 17 | 2.19.0 18 | 19 | 1.3 20 | 1.5.18 21 | 1.13 22 | 3.12.0 23 | 5.9.3 24 | 3.27.3 25 | 26 | 5.3 27 | 28 | 29 | 30 | 31 | 32 | org.slf4j 33 | slf4j-api 34 | ${slf4j.version} 35 | 36 | 37 | com.fasterxml.jackson 38 | jackson-bom 39 | ${jackson.version} 40 | import 41 | pom 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.slf4j 49 | slf4j-api 50 | 51 | 52 | 53 | com.fasterxml.jackson.core 54 | jackson-databind 55 | 56 | 57 | 58 | com.cosium.synapse_junit_extension 59 | synapse-junit-extension 60 | ${synapse-junit-extension.version} 61 | test 62 | 63 | 64 | ch.qos.logback 65 | logback-classic 66 | ${logback-classic.version} 67 | test 68 | 69 | 70 | org.junit.jupiter 71 | junit-jupiter 72 | ${junit.version} 73 | test 74 | 75 | 76 | org.assertj 77 | assertj-core 78 | ${assertj.version} 79 | test 80 | 81 | 82 | 83 | 84 | 85 | 86 | com.cosium.code 87 | git-code-format-maven-plugin 88 | ${git-code-format-maven-plugin.version} 89 | 90 | 91 | 92 | install-formatter-hook 93 | 94 | install-hooks 95 | 96 | 97 | 99 | 100 | validate-code-format 101 | 102 | validate-code-format 103 | 104 | 105 | 106 | 107 | 108 | 109 | com.cosium.code 110 | google-java-format 111 | ${git-code-format-maven-plugin.version} 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ./mvnw --batch-mode clean release:prepare release:perform && git push && git push --tags 3 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/AccessTokenFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | interface AccessTokenFactory { 7 | 8 | String build(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/AccessTokenFactoryFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | interface AccessTokenFactoryFactory { 7 | 8 | AccessTokenFactory build( 9 | HttpClientFactory httpClientFactory, JsonHandlers jsonHandlers, MatrixUris uris); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/AccessTokensResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | public interface AccessTokensResource { 7 | 8 | /** 9 | * @return An access token 10 | */ 11 | String create(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/ClientEvent.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | public class ClientEvent { 11 | 12 | private final ObjectMapper objectMapper; 13 | private final RawClientEvent raw; 14 | 15 | public ClientEvent(ObjectMapper objectMapper, RawClientEvent raw) { 16 | this.objectMapper = requireNonNull(objectMapper); 17 | this.raw = requireNonNull(raw); 18 | } 19 | 20 | public T content(Class contentType) { 21 | return objectMapper.convertValue(raw.content(), contentType); 22 | } 23 | 24 | public String id() { 25 | return raw.id(); 26 | } 27 | 28 | public long originServerTs() { 29 | return raw.originServerTs(); 30 | } 31 | 32 | public String roomId() { 33 | return raw.roomId(); 34 | } 35 | 36 | public String sender() { 37 | return raw.sender(); 38 | } 39 | 40 | public String stateKey() { 41 | return raw.stateKey(); 42 | } 43 | 44 | public String type() { 45 | return raw.type(); 46 | } 47 | 48 | public UnsignedData unsigned() { 49 | return new UnsignedData(objectMapper, raw.unsigned()); 50 | } 51 | 52 | public static class UnsignedData { 53 | private final ObjectMapper objectMapper; 54 | private final RawClientEvent.UnsignedData raw; 55 | 56 | public UnsignedData(ObjectMapper objectMapper, RawClientEvent.UnsignedData raw) { 57 | this.objectMapper = requireNonNull(objectMapper); 58 | this.raw = requireNonNull(raw); 59 | } 60 | 61 | public Long age() { 62 | return raw.age(); 63 | } 64 | 65 | public T previousContent(Class contentType) { 66 | return objectMapper.convertValue(raw.previousContent(), contentType); 67 | } 68 | 69 | public ClientEvent redactedBecause() { 70 | return new ClientEvent(objectMapper, raw.redactedBecause()); 71 | } 72 | 73 | public String transactionId() { 74 | return raw.transactionId(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/ClientEventPage.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | * @author Réda Housni Alaoui 11 | */ 12 | public class ClientEventPage { 13 | 14 | private final ObjectMapper objectMapper; 15 | private final RawClientEventPage raw; 16 | 17 | ClientEventPage(ObjectMapper objectMapper, RawClientEventPage raw) { 18 | this.objectMapper = requireNonNull(objectMapper); 19 | this.raw = requireNonNull(raw); 20 | } 21 | 22 | public List chunk() { 23 | return raw.chunk().stream() 24 | .map(rawClientEvent -> new ClientEvent(objectMapper, rawClientEvent)) 25 | .collect(Collectors.toUnmodifiableList()); 26 | } 27 | 28 | public String end() { 29 | return raw.end(); 30 | } 31 | 32 | public String start() { 33 | return raw.start(); 34 | } 35 | 36 | public List state() { 37 | return raw.state().stream() 38 | .map(rawClientEvent -> new ClientEvent(objectMapper, rawClientEvent)) 39 | .collect(Collectors.toUnmodifiableList()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/ClientEventResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | public interface ClientEventResource { 7 | 8 | ClientEvent fetch(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/CreateRoomInput.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | public class CreateRoomInput { 9 | 10 | private final CreationContent creationContent; 11 | private final String name; 12 | private final String preset; 13 | private final String roomAliasName; 14 | private final String topic; 15 | 16 | private CreateRoomInput(Builder builder) { 17 | creationContent = builder.creationContent; 18 | name = builder.name; 19 | preset = builder.preset; 20 | roomAliasName = builder.roomAliasName; 21 | topic = builder.topic; 22 | } 23 | 24 | public static Builder builder() { 25 | return new Builder(); 26 | } 27 | 28 | @JsonProperty("creation_content") 29 | public CreationContent creationContent() { 30 | return creationContent; 31 | } 32 | 33 | @JsonProperty("name") 34 | public String name() { 35 | return name; 36 | } 37 | 38 | @JsonProperty("preset") 39 | public String preset() { 40 | return preset; 41 | } 42 | 43 | @JsonProperty("room_alias_name") 44 | public String roomAliasName() { 45 | return roomAliasName; 46 | } 47 | 48 | @JsonProperty("topic") 49 | public String topic() { 50 | return topic; 51 | } 52 | 53 | public static class CreationContent { 54 | private final boolean federate; 55 | 56 | public CreationContent(boolean federate) { 57 | this.federate = federate; 58 | } 59 | 60 | @JsonProperty("m.federate") 61 | public boolean federate() { 62 | return federate; 63 | } 64 | } 65 | 66 | public static class Builder { 67 | 68 | private CreationContent creationContent = new CreationContent(false); 69 | private String name; 70 | private String preset = "public_chat"; 71 | private String roomAliasName; 72 | private String topic; 73 | 74 | private Builder() {} 75 | 76 | public Builder creationContent(CreationContent creationContent) { 77 | this.creationContent = creationContent; 78 | return this; 79 | } 80 | 81 | public Builder name(String name) { 82 | this.name = name; 83 | return this; 84 | } 85 | 86 | public Builder preset(String preset) { 87 | this.preset = preset; 88 | return this; 89 | } 90 | 91 | public Builder roomAliasName(String roomAliasName) { 92 | this.roomAliasName = roomAliasName; 93 | return this; 94 | } 95 | 96 | public Builder topic(String topic) { 97 | this.topic = topic; 98 | return this; 99 | } 100 | 101 | public CreateRoomInput build() { 102 | return new CreateRoomInput(this); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/CreateRoomOutput.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | /** 7 | * @author Réda Housni Alaoui 8 | */ 9 | class CreateRoomOutput { 10 | 11 | private final String roomId; 12 | 13 | @JsonCreator 14 | CreateRoomOutput(@JsonProperty("room_id") String roomId) { 15 | this.roomId = roomId; 16 | } 17 | 18 | public String roomId() { 19 | return roomId; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/CreatedEvent.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | class CreatedEvent { 9 | 10 | private final String id; 11 | 12 | public CreatedEvent(@JsonProperty("event_id") String id) { 13 | this.id = id; 14 | } 15 | 16 | public String id() { 17 | return id; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/HttpClientFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import java.net.http.HttpClient; 4 | import java.time.Duration; 5 | import java.util.Optional; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class HttpClientFactory { 11 | 12 | private final Duration connectTimeout; 13 | 14 | HttpClientFactory(Duration connectTimeout) { 15 | this.connectTimeout = connectTimeout; 16 | } 17 | 18 | public HttpClient build() { 19 | HttpClient.Builder builder = HttpClient.newBuilder(); 20 | Optional.ofNullable(connectTimeout).ifPresent(builder::connectTimeout); 21 | return builder.followRedirects(HttpClient.Redirect.NORMAL).build(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/JsonBody.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | class JsonBody { 7 | 8 | private final int responseStatusCode; 9 | private final T body; 10 | 11 | public JsonBody(int responseStatusCode, T body) { 12 | this.responseStatusCode = responseStatusCode; 13 | this.body = body; 14 | } 15 | 16 | public boolean isNotFound() { 17 | return responseStatusCode == 404; 18 | } 19 | 20 | public T parse() { 21 | if (responseStatusCode != 200) { 22 | throw new IllegalStateException( 23 | String.format("Response has status code %s instead of 200", responseStatusCode)); 24 | } 25 | return body; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/JsonHandlers.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.core.type.TypeReference; 7 | import com.fasterxml.jackson.databind.ObjectMapper; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.UncheckedIOException; 11 | import java.net.http.HttpRequest; 12 | import java.net.http.HttpResponse; 13 | import java.util.function.Supplier; 14 | 15 | /** 16 | * @author Réda Housni Alaoui 17 | */ 18 | class JsonHandlers { 19 | 20 | private final ObjectMapper objectMapper; 21 | 22 | public JsonHandlers(ObjectMapper objectMapper) { 23 | this.objectMapper = requireNonNull(objectMapper); 24 | } 25 | 26 | public HttpRequest.BodyPublisher publisher(Object value) { 27 | try { 28 | String json = objectMapper.writeValueAsString(value); 29 | return HttpRequest.BodyPublishers.ofString(json); 30 | } catch (JsonProcessingException e) { 31 | throw new UncheckedIOException(e); 32 | } 33 | } 34 | 35 | public HttpResponse.BodyHandler>> handler(Class type) { 36 | return responseInfo -> 37 | createBodySubscriber( 38 | responseInfo, inputStream -> objectMapper.readValue(inputStream, type)); 39 | } 40 | 41 | public HttpResponse.BodyHandler>> handler(TypeReference type) { 42 | return responseInfo -> 43 | createBodySubscriber( 44 | responseInfo, inputStream -> objectMapper.readValue(inputStream, type)); 45 | } 46 | 47 | private HttpResponse.BodySubscriber>> createBodySubscriber( 48 | HttpResponse.ResponseInfo responseInfo, ContentParser contentParser) { 49 | int statusCode = responseInfo.statusCode(); 50 | if (statusCode != 200) { 51 | return HttpResponse.BodySubscribers.replacing(() -> new JsonBody<>(statusCode, null)); 52 | } 53 | 54 | return HttpResponse.BodySubscribers.mapping( 55 | HttpResponse.BodySubscribers.ofInputStream(), 56 | is -> 57 | () -> { 58 | try (InputStream inputStream = is) { 59 | return new JsonBody<>(statusCode, contentParser.parse(inputStream)); 60 | } catch (IOException e) { 61 | throw new UncheckedIOException(e); 62 | } 63 | }); 64 | } 65 | 66 | private interface ContentParser { 67 | T parse(InputStream inputStream) throws IOException; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/Lazy.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | import java.util.function.Supplier; 8 | 9 | /** 10 | * @author Réda Housni Alaoui 11 | */ 12 | class Lazy implements Supplier { 13 | private static final String CACHE_KEY = String.valueOf(0); 14 | private final Map cache = new ConcurrentHashMap<>(); 15 | 16 | private final Supplier factory; 17 | 18 | private Lazy(Supplier factory) { 19 | this.factory = requireNonNull(factory); 20 | } 21 | 22 | public static Lazy of(Supplier factory) { 23 | return new Lazy<>(factory); 24 | } 25 | 26 | @Override 27 | public T get() { 28 | return cache.computeIfAbsent(CACHE_KEY, k -> factory.get()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/LoginInput.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | class LoginInput { 9 | 10 | private final String type; 11 | private final Identifier identifier; 12 | private final String password; 13 | 14 | LoginInput(String type, Identifier identifier, String password) { 15 | this.type = type; 16 | this.identifier = identifier; 17 | this.password = password; 18 | } 19 | 20 | @JsonProperty("type") 21 | public String type() { 22 | return type; 23 | } 24 | 25 | @JsonProperty("identifier") 26 | public Identifier identifier() { 27 | return identifier; 28 | } 29 | 30 | @JsonProperty("password") 31 | public String password() { 32 | return password; 33 | } 34 | 35 | static class Identifier { 36 | private final String type; 37 | private final String user; 38 | 39 | Identifier(String type, String user) { 40 | this.type = type; 41 | this.user = user; 42 | } 43 | 44 | @JsonProperty("type") 45 | public String type() { 46 | return type; 47 | } 48 | 49 | @JsonProperty("user") 50 | public String user() { 51 | return user; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/LoginOutput.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | /** 7 | * @author Réda Housni Alaoui 8 | */ 9 | class LoginOutput { 10 | 11 | private final String accessToken; 12 | 13 | @JsonCreator 14 | LoginOutput(@JsonProperty("access_token") String accessToken) { 15 | this.accessToken = accessToken; 16 | } 17 | 18 | public String accessToken() { 19 | return accessToken; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixApi.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.io.IOException; 6 | import java.net.URI; 7 | import java.net.http.HttpClient; 8 | import java.net.http.HttpRequest; 9 | import java.util.UUID; 10 | 11 | /** 12 | * @author Réda Housni Alaoui 13 | */ 14 | class MatrixApi { 15 | 16 | private static final String APPLICATION_JSON = "application/json"; 17 | private final HttpClient httpClient; 18 | private final JsonHandlers jsonHandlers; 19 | private final MatrixUri baseUri; 20 | private final AccessTokenFactory accessTokenFactory; 21 | 22 | private MatrixApi( 23 | HttpClientFactory httpClientFactory, 24 | JsonHandlers jsonHandlers, 25 | MatrixUris uris, 26 | AccessTokenFactory accessTokenFactory) { 27 | httpClient = httpClientFactory.build(); 28 | this.jsonHandlers = requireNonNull(jsonHandlers); 29 | baseUri = uris.fetchBaseUri(httpClient, jsonHandlers); 30 | this.accessTokenFactory = requireNonNull(accessTokenFactory); 31 | } 32 | 33 | public static MatrixApi load( 34 | HttpClientFactory httpClientFactory, 35 | JsonHandlers jsonHandlers, 36 | MatrixUris uris, 37 | AccessTokenFactory accessTokenFactory) { 38 | return new MatrixApi(httpClientFactory, jsonHandlers, uris, accessTokenFactory); 39 | } 40 | 41 | public CreatedEvent sendMessageToRoom(Message input, String roomId) { 42 | 43 | HttpRequest request = 44 | HttpRequest.newBuilder() 45 | .uri( 46 | baseUri 47 | .addPathSegments( 48 | "rooms", roomId, "send", "m.room.message", UUID.randomUUID().toString()) 49 | .toUri()) 50 | .header("Authorization", String.format("Bearer %s", accessTokenFactory.build())) 51 | .header("Content-Type", APPLICATION_JSON) 52 | .header("Accept", APPLICATION_JSON) 53 | .PUT(jsonHandlers.publisher(input)) 54 | .build(); 55 | 56 | try { 57 | return httpClient 58 | .send(request, jsonHandlers.handler(CreatedEvent.class)) 59 | .body() 60 | .get() 61 | .parse(); 62 | } catch (IOException e) { 63 | throw new RuntimeException(e); 64 | } catch (InterruptedException e) { 65 | Thread.currentThread().interrupt(); 66 | throw new RuntimeException(e); 67 | } 68 | } 69 | 70 | public CreateRoomOutput createRoom(CreateRoomInput input) { 71 | HttpRequest request = 72 | HttpRequest.newBuilder() 73 | .uri(baseUri.addPathSegments("createRoom").toUri()) 74 | .header("Authorization", String.format("Bearer %s", accessTokenFactory.build())) 75 | .header("Content-Type", APPLICATION_JSON) 76 | .header("Accept", APPLICATION_JSON) 77 | .POST(jsonHandlers.publisher(input)) 78 | .build(); 79 | 80 | try { 81 | return httpClient 82 | .send(request, jsonHandlers.handler(CreateRoomOutput.class)) 83 | .body() 84 | .get() 85 | .parse(); 86 | } catch (IOException e) { 87 | throw new RuntimeException(e); 88 | } catch (InterruptedException e) { 89 | Thread.currentThread().interrupt(); 90 | throw new RuntimeException(e); 91 | } 92 | } 93 | 94 | public RawClientEvent fetchEvent(String roomId, String eventId) { 95 | HttpRequest request = 96 | HttpRequest.newBuilder() 97 | .uri(baseUri.addPathSegments("rooms", roomId, "event", eventId).toUri()) 98 | .header("Authorization", String.format("Bearer %s", accessTokenFactory.build())) 99 | .header("Accept", APPLICATION_JSON) 100 | .GET() 101 | .build(); 102 | 103 | try { 104 | return httpClient 105 | .send(request, jsonHandlers.handler(RawClientEvent.class)) 106 | .body() 107 | .get() 108 | .parse(); 109 | } catch (IOException e) { 110 | throw new RuntimeException(e); 111 | } catch (InterruptedException e) { 112 | Thread.currentThread().interrupt(); 113 | throw new RuntimeException(e); 114 | } 115 | } 116 | 117 | public RawClientEventPage fetchMessagePage( 118 | String roomId, String dir, String from, String limit, String to) { 119 | URI uri = 120 | baseUri 121 | .addPathSegments("rooms", roomId, "messages") 122 | .addQueryParameter("dir", dir) 123 | .addQueryParameter("from", from) 124 | .addQueryParameter("limit", limit) 125 | .addQueryParameter("to", to) 126 | .toUri(); 127 | HttpRequest request = 128 | HttpRequest.newBuilder() 129 | .uri(uri) 130 | .header("Authorization", String.format("Bearer %s", accessTokenFactory.build())) 131 | .header("Accept", APPLICATION_JSON) 132 | .GET() 133 | .build(); 134 | 135 | try { 136 | return httpClient 137 | .send(request, jsonHandlers.handler(RawClientEventPage.class)) 138 | .body() 139 | .get() 140 | .parse(); 141 | } catch (IOException e) { 142 | throw new RuntimeException(e); 143 | } catch (InterruptedException e) { 144 | Thread.currentThread().interrupt(); 145 | throw new RuntimeException(e); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixHostname.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.util.Optional; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class MatrixHostname { 11 | 12 | private final String value; 13 | 14 | public MatrixHostname(String value) { 15 | this.value = requireNonNull(value); 16 | } 17 | 18 | public MatrixUri createUri(boolean https, Integer port, String... pathSegments) { 19 | StringBuilder uriBuilder = new StringBuilder(); 20 | if (https) { 21 | uriBuilder.append("https://"); 22 | } else { 23 | uriBuilder.append("http://"); 24 | } 25 | uriBuilder.append(value); 26 | Optional.ofNullable(port).ifPresent(aPort -> uriBuilder.append(":").append(aPort)); 27 | 28 | return new MatrixUri(uriBuilder.toString()).addPathSegments(pathSegments); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixResources.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | public interface MatrixResources { 7 | 8 | static MatrixResourcesFactory factory() { 9 | return new MatrixResourcesFactory(); 10 | } 11 | 12 | AccessTokensResource accessTokens(); 13 | 14 | RoomsResource rooms(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixResourcesFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import java.time.Duration; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | /** 7 | * @author Réda Housni Alaoui 8 | */ 9 | public class MatrixResourcesFactory { 10 | 11 | public HttpsBuilder builder() { 12 | return new MatrixResourcesBuilder(); 13 | } 14 | 15 | public interface HttpsBuilder { 16 | HostnameBuilder https(boolean https); 17 | 18 | default HostnameBuilder https() { 19 | return https(true); 20 | } 21 | 22 | default HostnameBuilder http() { 23 | return https(false); 24 | } 25 | } 26 | 27 | public interface HostnameBuilder { 28 | PortBuilder hostname(String hostname); 29 | } 30 | 31 | public interface PortBuilder { 32 | 33 | AuthenticationBuilder port(Integer port); 34 | 35 | default AuthenticationBuilder defaultPort() { 36 | return port(null); 37 | } 38 | } 39 | 40 | public interface AuthenticationBuilder { 41 | FinalBuilder accessToken(String accessToken); 42 | 43 | FinalBuilder usernamePassword(String username, String password); 44 | } 45 | 46 | public interface FinalBuilder { 47 | 48 | FinalBuilder connectTimeout(Duration connectTimeout); 49 | 50 | MatrixResources build(); 51 | } 52 | 53 | private static class MatrixResourcesBuilder 54 | implements HttpsBuilder, HostnameBuilder, PortBuilder, AuthenticationBuilder, FinalBuilder { 55 | 56 | private boolean https = true; 57 | private String hostname; 58 | private Integer port; 59 | private Duration connectTimeout = Duration.of(30, ChronoUnit.SECONDS); 60 | private AccessTokenFactoryFactory accessTokenFactoryFactory; 61 | 62 | @Override 63 | public MatrixResourcesBuilder https(boolean https) { 64 | this.https = https; 65 | return this; 66 | } 67 | 68 | @Override 69 | public MatrixResourcesBuilder hostname(String hostname) { 70 | this.hostname = hostname; 71 | return this; 72 | } 73 | 74 | @Override 75 | public MatrixResourcesBuilder port(Integer port) { 76 | this.port = port; 77 | return this; 78 | } 79 | 80 | @Override 81 | public MatrixResourcesBuilder accessToken(String accessToken) { 82 | accessTokenFactoryFactory = (h, j, u) -> () -> accessToken; 83 | return this; 84 | } 85 | 86 | @Override 87 | public FinalBuilder usernamePassword(String username, String password) { 88 | accessTokenFactoryFactory = new UsernamePasswordAccessTokenFactoryFactory(username, password); 89 | return this; 90 | } 91 | 92 | @Override 93 | public FinalBuilder connectTimeout(Duration connectTimeout) { 94 | this.connectTimeout = connectTimeout; 95 | return this; 96 | } 97 | 98 | public MatrixResources build() { 99 | return new SimpleMatrixResources( 100 | https, hostname, port, connectTimeout, accessTokenFactoryFactory); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixUnprotectedApi.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.io.IOException; 6 | import java.net.http.HttpClient; 7 | import java.net.http.HttpRequest; 8 | 9 | /** 10 | * @author Réda Housni Alaoui 11 | */ 12 | class MatrixUnprotectedApi { 13 | 14 | private final HttpClient httpClient; 15 | private final JsonHandlers jsonHandlers; 16 | private final MatrixUri baseUri; 17 | 18 | private MatrixUnprotectedApi( 19 | HttpClientFactory httpClientFactory, JsonHandlers jsonHandlers, MatrixUris uris) { 20 | httpClient = httpClientFactory.build(); 21 | this.jsonHandlers = requireNonNull(jsonHandlers); 22 | baseUri = uris.fetchBaseUri(httpClient, jsonHandlers); 23 | } 24 | 25 | public static MatrixUnprotectedApi load( 26 | HttpClientFactory httpClientFactory, JsonHandlers jsonHandlers, MatrixUris uris) { 27 | return new MatrixUnprotectedApi(httpClientFactory, jsonHandlers, uris); 28 | } 29 | 30 | public LoginOutput login(LoginInput loginInput) { 31 | HttpRequest loginRequest = 32 | HttpRequest.newBuilder(baseUri.addPathSegments("login").toUri()) 33 | .header("Content-Type", "application/json") 34 | .header("Accept", "application/json") 35 | .POST(jsonHandlers.publisher(loginInput)) 36 | .build(); 37 | 38 | try { 39 | return httpClient 40 | .send(loginRequest, jsonHandlers.handler(LoginOutput.class)) 41 | .body() 42 | .get() 43 | .parse(); 44 | } catch (IOException e) { 45 | throw new RuntimeException(e); 46 | } catch (InterruptedException e) { 47 | Thread.currentThread().interrupt(); 48 | throw new RuntimeException(e); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixUri.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.util.stream.Stream; 8 | 9 | /** 10 | * @author Réda Housni Alaoui 11 | */ 12 | class MatrixUri { 13 | 14 | private final URI uriValue; 15 | 16 | public MatrixUri(String value) { 17 | this(URI.create(value)); 18 | } 19 | 20 | public MatrixUri(URI value) { 21 | this.uriValue = requireNonNull(value); 22 | } 23 | 24 | public MatrixUri addPathSegments(String... pathSegment) { 25 | String genuinePath = uriValue.getPath(); 26 | if (genuinePath.endsWith("/")) { 27 | genuinePath = genuinePath.substring(0, genuinePath.length() - 1); 28 | } 29 | 30 | StringBuilder pathBuilder = new StringBuilder(genuinePath); 31 | 32 | Stream.of(pathSegment) 33 | .map(String::trim) 34 | .map(this::assertValidPathSegment) 35 | .map(segment -> String.format("/%s", segment)) 36 | .forEach(pathBuilder::append); 37 | 38 | try { 39 | return new MatrixUri( 40 | new URI( 41 | uriValue.getScheme(), 42 | uriValue.getUserInfo(), 43 | uriValue.getHost(), 44 | uriValue.getPort(), 45 | pathBuilder.toString(), 46 | uriValue.getQuery(), 47 | uriValue.getFragment())); 48 | } catch (URISyntaxException e) { 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | 53 | public MatrixUri addQueryParameter(String name, String value) { 54 | if (value == null) { 55 | return this; 56 | } 57 | 58 | String genuineQuery = uriValue.getQuery(); 59 | StringBuilder newQuery; 60 | if (genuineQuery != null && !genuineQuery.isBlank()) { 61 | newQuery = new StringBuilder(uriValue.getQuery()).append("&"); 62 | } else { 63 | newQuery = new StringBuilder(); 64 | } 65 | newQuery.append(name).append("=").append(value); 66 | 67 | try { 68 | return new MatrixUri( 69 | new URI( 70 | uriValue.getScheme(), 71 | uriValue.getUserInfo(), 72 | uriValue.getHost(), 73 | uriValue.getPort(), 74 | uriValue.getPath(), 75 | newQuery.toString(), 76 | uriValue.getFragment())); 77 | } catch (URISyntaxException e) { 78 | throw new RuntimeException(e); 79 | } 80 | } 81 | 82 | private String assertValidPathSegment(String segment) { 83 | if (segment == null) { 84 | throw new IllegalArgumentException("The segment should not be null"); 85 | } 86 | if (segment.isBlank()) { 87 | throw new IllegalArgumentException("The segment should not be blank"); 88 | } 89 | if (segment.contains("/")) { 90 | throw new IllegalArgumentException( 91 | String.format("Segment '%s' should not contain '/'", segment)); 92 | } 93 | return segment; 94 | } 95 | 96 | public URI toUri() { 97 | return uriValue; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/MatrixUris.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import java.net.http.HttpClient; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class MatrixUris { 11 | 12 | private final boolean https; 13 | private final MatrixHostname hostname; 14 | private final Integer port; 15 | 16 | public MatrixUris(boolean https, MatrixHostname hostname, Integer port) { 17 | this.https = https; 18 | this.hostname = requireNonNull(hostname); 19 | this.port = port; 20 | } 21 | 22 | public MatrixUri create(String... paths) { 23 | return hostname.createUri(https, port, paths); 24 | } 25 | 26 | public MatrixUri fetchBaseUri(HttpClient httpClient, JsonHandlers jsonHandlers) { 27 | return WellKnownMatrixClient.fetch(httpClient, jsonHandlers, this) 28 | .map(WellKnownMatrixClient::homeServer) 29 | .map(WellKnownMatrixClient.HomeServer::baseUri) 30 | .orElseGet(this::create) 31 | .addPathSegments("_matrix", "client", "v3"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/Message.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | public class Message { 11 | 12 | private final String body; 13 | private final String format; 14 | private final String formattedBody; 15 | private final String type; 16 | 17 | private Message(Builder builder) { 18 | body = builder.body; 19 | format = builder.format; 20 | formattedBody = builder.formattedBody; 21 | type = builder.type; 22 | } 23 | 24 | @JsonCreator 25 | Message( 26 | @JsonProperty("body") String body, 27 | @JsonProperty("format") String format, 28 | @JsonProperty("formatted_body") String formattedBody, 29 | @JsonProperty("msgtype") String type) { 30 | this.body = body; 31 | this.format = format; 32 | this.formattedBody = formattedBody; 33 | this.type = type; 34 | } 35 | 36 | public static Builder builder() { 37 | return new Builder(); 38 | } 39 | 40 | @JsonProperty("body") 41 | public String body() { 42 | return body; 43 | } 44 | 45 | @JsonProperty("format") 46 | public String format() { 47 | return format; 48 | } 49 | 50 | @JsonProperty("formatted_body") 51 | public String formattedBody() { 52 | return formattedBody; 53 | } 54 | 55 | @JsonProperty("msgtype") 56 | public String type() { 57 | return type; 58 | } 59 | 60 | @Override 61 | public int hashCode() { 62 | return Objects.hash(body, format, formattedBody, type); 63 | } 64 | 65 | public static final class Builder { 66 | private String body; 67 | private String format = "org.matrix.custom.html"; 68 | private String formattedBody; 69 | private String type = "m.text"; 70 | 71 | private Builder() {} 72 | 73 | public Builder body(String body) { 74 | this.body = body; 75 | return this; 76 | } 77 | 78 | public Builder format(String format) { 79 | this.format = format; 80 | return this; 81 | } 82 | 83 | public Builder formattedBody(String formattedBody) { 84 | this.formattedBody = formattedBody; 85 | return this; 86 | } 87 | 88 | public Builder type(String type) { 89 | this.type = type; 90 | return this; 91 | } 92 | 93 | public Message build() { 94 | return new Message(this); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/RawClientEvent.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.annotation.JsonCreator; 6 | import com.fasterxml.jackson.annotation.JsonProperty; 7 | import com.fasterxml.jackson.databind.node.ObjectNode; 8 | 9 | /** 10 | * @author Réda Housni Alaoui 11 | */ 12 | class RawClientEvent { 13 | 14 | private final ObjectNode content; 15 | private final String id; 16 | private final long originServerTs; 17 | private final String roomId; 18 | private final String sender; 19 | private final String stateKey; 20 | private final String type; 21 | private final UnsignedData unsigned; 22 | 23 | @JsonCreator 24 | RawClientEvent( 25 | @JsonProperty("content") ObjectNode content, 26 | @JsonProperty("event_id") String id, 27 | @JsonProperty("origin_server_ts") long originServerTs, 28 | @JsonProperty("room_id") String roomId, 29 | @JsonProperty("sender") String sender, 30 | @JsonProperty("state_key") String stateKey, 31 | @JsonProperty("type") String type, 32 | @JsonProperty("unsigned") UnsignedData unsigned) { 33 | this.content = requireNonNull(content); 34 | this.id = requireNonNull(id); 35 | this.originServerTs = originServerTs; 36 | this.roomId = requireNonNull(roomId); 37 | this.sender = requireNonNull(sender); 38 | this.stateKey = stateKey; 39 | this.type = requireNonNull(type); 40 | this.unsigned = unsigned; 41 | } 42 | 43 | public ObjectNode content() { 44 | return content; 45 | } 46 | 47 | public String id() { 48 | return id; 49 | } 50 | 51 | public long originServerTs() { 52 | return originServerTs; 53 | } 54 | 55 | public String roomId() { 56 | return roomId; 57 | } 58 | 59 | public String sender() { 60 | return sender; 61 | } 62 | 63 | public String stateKey() { 64 | return stateKey; 65 | } 66 | 67 | public String type() { 68 | return type; 69 | } 70 | 71 | public UnsignedData unsigned() { 72 | return unsigned; 73 | } 74 | 75 | public static class UnsignedData { 76 | private final Long age; 77 | private final ObjectNode previousContent; 78 | private final RawClientEvent redactedBecause; 79 | private final String transactionId; 80 | 81 | public UnsignedData( 82 | @JsonProperty("age") Long age, 83 | @JsonProperty("prev_content") ObjectNode previousContent, 84 | @JsonProperty("redacted_because") RawClientEvent redactedBecause, 85 | @JsonProperty("transaction_id") String transactionId) { 86 | this.age = age; 87 | this.previousContent = previousContent; 88 | this.redactedBecause = redactedBecause; 89 | this.transactionId = transactionId; 90 | } 91 | 92 | public Long age() { 93 | return age; 94 | } 95 | 96 | public ObjectNode previousContent() { 97 | return previousContent; 98 | } 99 | 100 | public RawClientEvent redactedBecause() { 101 | return redactedBecause; 102 | } 103 | 104 | public String transactionId() { 105 | return transactionId; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/RawClientEventPage.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | /** 9 | * @author Réda Housni Alaoui 10 | */ 11 | class RawClientEventPage { 12 | 13 | private final List chunk; 14 | private final String end; 15 | private final String start; 16 | private final List state; 17 | 18 | @JsonCreator 19 | RawClientEventPage( 20 | @JsonProperty("chunk") List chunk, 21 | @JsonProperty("end") String end, 22 | @JsonProperty("start") String start, 23 | @JsonProperty("state") List state) { 24 | this.chunk = Optional.ofNullable(chunk).map(List::copyOf).orElseGet(List::of); 25 | this.end = end; 26 | this.start = start; 27 | this.state = Optional.ofNullable(state).map(List::copyOf).orElseGet(List::of); 28 | } 29 | 30 | public List chunk() { 31 | return chunk; 32 | } 33 | 34 | public String end() { 35 | return end; 36 | } 37 | 38 | public String start() { 39 | return start; 40 | } 41 | 42 | public List state() { 43 | return state; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/ResponseInfo.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import java.net.http.HttpResponse; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | public class ResponseInfo { 9 | 10 | private final HttpResponse.ResponseInfo responseInfo; 11 | 12 | public ResponseInfo(HttpResponse.ResponseInfo responseInfo) { 13 | this.responseInfo = responseInfo; 14 | } 15 | 16 | public static HttpResponse.BodyHandler handler() { 17 | return responseInfo -> HttpResponse.BodySubscribers.replacing(new ResponseInfo(responseInfo)); 18 | } 19 | 20 | public ResponseInfo assertSuccess() { 21 | int statusCode = responseInfo.statusCode(); 22 | if (statusCode >= 200 && statusCode < 400) { 23 | return this; 24 | } 25 | throw new IllegalStateException(String.format("Response failed with code %s", statusCode)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/RoomResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | public interface RoomResource { 7 | 8 | String id(); 9 | 10 | /** 11 | * https://spec.matrix.org/latest/client-server-api/#mroommessage 13 | */ 14 | ClientEventResource sendMessage(Message messageInput); 15 | 16 | /** 17 | * @param dir The direction to return events from. If this is set to f, events will be returned in 18 | * chronological order starting at from. If it is set to b, events will be returned in reverse 19 | * chronological order, again starting at from. One of: [b, f]. 20 | * @param from The token to start returning events from. This token can be obtained from a 21 | * prev_batch or next_batch token returned by the /sync endpoint, or from an end token 22 | * returned by a previous request to this endpoint. 23 | *

This endpoint can also accept a value returned as a start token by a previous request to 24 | * this endpoint, though servers are not required to support this. Clients should not rely on 25 | * the behaviour. 26 | *

If it is not provided, the homeserver shall return a list of messages from the first or 27 | * last (per the value of the dir parameter) visible event in the room history for the 28 | * requesting user. 29 | * @param limit The maximum number of events to return. 30 | * @param to The token to stop returning events at. This token can be obtained from a prev_batch 31 | * or next_batch token returned by the /sync endpoint, or from an end token returned by a 32 | * previous request to this endpoint. 33 | * @return A page of events 34 | */ 35 | ClientEventPage fetchEventPage(String dir, String from, Long limit, String to); 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/RoomsResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | public interface RoomsResource { 7 | 8 | RoomResource byId(String id); 9 | 10 | RoomResource create(CreateRoomInput input); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/SimpleAccessTokensResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | class SimpleAccessTokensResource implements AccessTokensResource { 9 | 10 | private final AccessTokenFactory accessTokenFactory; 11 | 12 | SimpleAccessTokensResource(AccessTokenFactory accessTokenFactory) { 13 | this.accessTokenFactory = requireNonNull(accessTokenFactory); 14 | } 15 | 16 | @Override 17 | public String create() { 18 | return accessTokenFactory.build(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/SimpleClientEventResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class SimpleClientEventResource implements ClientEventResource { 11 | 12 | private final Lazy api; 13 | private final ObjectMapper objectMapper; 14 | private final String roomId; 15 | private final String id; 16 | 17 | public SimpleClientEventResource( 18 | Lazy api, ObjectMapper objectMapper, String roomId, String id) { 19 | this.api = requireNonNull(api); 20 | this.objectMapper = requireNonNull(objectMapper); 21 | this.roomId = requireNonNull(roomId); 22 | this.id = requireNonNull(id); 23 | } 24 | 25 | @Override 26 | public ClientEvent fetch() { 27 | return new ClientEvent(objectMapper, api.get().fetchEvent(roomId, id)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/SimpleMatrixResources.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import java.time.Duration; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class SimpleMatrixResources implements MatrixResources { 11 | 12 | private final ObjectMapper objectMapper; 13 | private final AccessTokenFactory accessTokenFactory; 14 | private final Lazy api; 15 | 16 | public SimpleMatrixResources( 17 | boolean https, 18 | String hostname, 19 | Integer port, 20 | Duration connectTimeout, 21 | AccessTokenFactoryFactory accessTokenFactoryFactory) { 22 | objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 23 | MatrixUris matrixUris = new MatrixUris(https, new MatrixHostname(hostname), port); 24 | JsonHandlers jsonHandlers = new JsonHandlers(objectMapper); 25 | HttpClientFactory httpClientFactory = new HttpClientFactory(connectTimeout); 26 | accessTokenFactory = 27 | accessTokenFactoryFactory.build(httpClientFactory, jsonHandlers, matrixUris); 28 | api = 29 | Lazy.of( 30 | () -> MatrixApi.load(httpClientFactory, jsonHandlers, matrixUris, accessTokenFactory)); 31 | } 32 | 33 | @Override 34 | public AccessTokensResource accessTokens() { 35 | return new SimpleAccessTokensResource(accessTokenFactory); 36 | } 37 | 38 | @Override 39 | public RoomsResource rooms() { 40 | return new SimpleRoomsResource(api, objectMapper); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/SimpleRoomResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | import static java.util.Optional.ofNullable; 5 | 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | 8 | /** 9 | * @author Réda Housni Alaoui 10 | */ 11 | class SimpleRoomResource implements RoomResource { 12 | 13 | private final Lazy api; 14 | private final ObjectMapper objectMapper; 15 | private final String id; 16 | 17 | public SimpleRoomResource(Lazy api, ObjectMapper objectMapper, String id) { 18 | this.api = requireNonNull(api); 19 | this.objectMapper = requireNonNull(objectMapper); 20 | this.id = requireNonNull(id); 21 | } 22 | 23 | @Override 24 | public String id() { 25 | return id; 26 | } 27 | 28 | @Override 29 | public ClientEventResource sendMessage(Message message) { 30 | CreatedEvent createdEvent = api.get().sendMessageToRoom(message, id); 31 | return new SimpleClientEventResource(api, objectMapper, id, createdEvent.id()); 32 | } 33 | 34 | @Override 35 | public ClientEventPage fetchEventPage(String dir, String from, Long limit, String to) { 36 | RawClientEventPage raw = 37 | api.get() 38 | .fetchMessagePage( 39 | id, dir, from, ofNullable(limit).map(String::valueOf).orElse(null), to); 40 | return new ClientEventPage(objectMapper, raw); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/SimpleRoomsResource.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | /** 8 | * @author Réda Housni Alaoui 9 | */ 10 | class SimpleRoomsResource implements RoomsResource { 11 | 12 | private final Lazy api; 13 | private final ObjectMapper objectMapper; 14 | 15 | SimpleRoomsResource(Lazy api, ObjectMapper objectMapper) { 16 | this.api = requireNonNull(api); 17 | this.objectMapper = requireNonNull(objectMapper); 18 | } 19 | 20 | @Override 21 | public RoomResource byId(String id) { 22 | return new SimpleRoomResource(api, objectMapper, id); 23 | } 24 | 25 | @Override 26 | public RoomResource create(CreateRoomInput input) { 27 | return new SimpleRoomResource(api, objectMapper, api.get().createRoom(input).roomId()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/UsernamePasswordAccessTokenFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | /** 4 | * @author Réda Housni Alaoui 5 | */ 6 | class UsernamePasswordAccessTokenFactory implements AccessTokenFactory { 7 | 8 | private final Lazy accessToken; 9 | 10 | public UsernamePasswordAccessTokenFactory( 11 | Lazy api, String username, String password) { 12 | accessToken = 13 | Lazy.of( 14 | () -> 15 | api.get() 16 | .login( 17 | new LoginInput( 18 | "m.login.password", 19 | new LoginInput.Identifier("m.id.user", username), 20 | password)) 21 | .accessToken()); 22 | } 23 | 24 | @Override 25 | public String build() { 26 | return accessToken.get(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/UsernamePasswordAccessTokenFactoryFactory.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | /** 6 | * @author Réda Housni Alaoui 7 | */ 8 | class UsernamePasswordAccessTokenFactoryFactory implements AccessTokenFactoryFactory { 9 | 10 | private final String username; 11 | private final String password; 12 | 13 | UsernamePasswordAccessTokenFactoryFactory(String username, String password) { 14 | this.username = requireNonNull(username); 15 | this.password = requireNonNull(password); 16 | } 17 | 18 | @Override 19 | public AccessTokenFactory build( 20 | HttpClientFactory httpClientFactory, JsonHandlers jsonHandlers, MatrixUris uris) { 21 | return new UsernamePasswordAccessTokenFactory( 22 | Lazy.of(() -> MatrixUnprotectedApi.load(httpClientFactory, jsonHandlers, uris)), 23 | username, 24 | password); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/cosium/matrix_communication_client/WellKnownMatrixClient.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | 5 | import com.fasterxml.jackson.annotation.JsonCreator; 6 | import com.fasterxml.jackson.annotation.JsonProperty; 7 | import java.io.IOException; 8 | import java.io.UncheckedIOException; 9 | import java.net.http.HttpClient; 10 | import java.net.http.HttpRequest; 11 | import java.util.Optional; 12 | 13 | /** 14 | * @author Réda Housni Alaoui 15 | */ 16 | class WellKnownMatrixClient { 17 | 18 | private final HomeServer homeServer; 19 | 20 | @JsonCreator 21 | WellKnownMatrixClient(@JsonProperty("m.homeserver") HomeServer homeServer) { 22 | this.homeServer = requireNonNull(homeServer); 23 | } 24 | 25 | public static Optional fetch( 26 | HttpClient httpClient, JsonHandlers jsonHandlers, MatrixUris matrixUris) { 27 | MatrixUri uri = matrixUris.create(".well-known", "matrix", "client"); 28 | try { 29 | JsonBody response = 30 | httpClient 31 | .send( 32 | HttpRequest.newBuilder(uri.toUri()) 33 | .header("Accept", "application/json") 34 | .GET() 35 | .build(), 36 | jsonHandlers.handler(WellKnownMatrixClient.class)) 37 | .body() 38 | .get(); 39 | if (response.isNotFound()) { 40 | return Optional.empty(); 41 | } 42 | return Optional.of(response.parse()); 43 | } catch (IOException e) { 44 | throw new UncheckedIOException(e); 45 | } catch (InterruptedException e) { 46 | Thread.currentThread().interrupt(); 47 | throw new RuntimeException(e); 48 | } 49 | } 50 | 51 | public HomeServer homeServer() { 52 | return homeServer; 53 | } 54 | 55 | public static class HomeServer { 56 | private final String baseUrl; 57 | 58 | @JsonCreator 59 | HomeServer(@JsonProperty("base_url") String baseUrl) { 60 | this.baseUrl = requireNonNull(baseUrl); 61 | } 62 | 63 | public MatrixUri baseUri() { 64 | return new MatrixUri(baseUrl); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/cosium/matrix_communication_client/AccessTokensResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static org.assertj.core.api.Assertions.assertThatCode; 4 | 5 | import com.cosium.synapse_junit_extension.EnableSynapse; 6 | import com.cosium.synapse_junit_extension.Synapse; 7 | import java.util.UUID; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Test; 11 | 12 | /** 13 | * @author Réda Housni Alaoui 14 | */ 15 | @EnableSynapse 16 | class AccessTokensResourceTest { 17 | private Synapse synapse; 18 | 19 | @BeforeEach 20 | void beforeEach(Synapse synapse) { 21 | this.synapse = synapse; 22 | } 23 | 24 | @Test 25 | @DisplayName("Create room") 26 | void test1() { 27 | String accessToken = 28 | newResourcesBuilder() 29 | .usernamePassword(synapse.adminUsername(), synapse.adminPassword()) 30 | .build() 31 | .accessTokens() 32 | .create(); 33 | 34 | CreateRoomInput createRoomInput = 35 | CreateRoomInput.builder() 36 | .name(UUID.randomUUID().toString()) 37 | .roomAliasName(UUID.randomUUID().toString()) 38 | .topic(UUID.randomUUID().toString()) 39 | .build(); 40 | RoomsResource rooms = newResourcesBuilder().accessToken(accessToken).build().rooms(); 41 | assertThatCode(() -> rooms.create(createRoomInput)).doesNotThrowAnyException(); 42 | } 43 | 44 | private MatrixResourcesFactory.AuthenticationBuilder newResourcesBuilder() { 45 | return MatrixResources.factory() 46 | .builder() 47 | .https(synapse.https()) 48 | .hostname(synapse.hostname()) 49 | .port(synapse.port()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/cosium/matrix_communication_client/LogbackConfigurator.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import ch.qos.logback.classic.BasicConfigurator; 4 | import ch.qos.logback.classic.Level; 5 | import ch.qos.logback.classic.LoggerContext; 6 | import java.util.Optional; 7 | 8 | /** 9 | * @author Réda Housni Alaoui 10 | */ 11 | public class LogbackConfigurator extends BasicConfigurator { 12 | 13 | @Override 14 | public ExecutionStatus configure(LoggerContext lc) { 15 | super.configure(lc); 16 | Level rootLevel = 17 | Optional.ofNullable(System.getenv("MATRIX_COMMUNICATION_CLIENT_TEST_LOG_ROOT_LEVEL")) 18 | .map(Level::valueOf) 19 | .orElse(Level.OFF); 20 | lc.getLogger("ROOT").setLevel(rootLevel); 21 | return ExecutionStatus.DO_NOT_INVOKE_NEXT_IF_ANY; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/cosium/matrix_communication_client/RoomResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.cosium.matrix_communication_client; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.api.Assertions.assertThatCode; 5 | import static org.assertj.core.api.Assertions.tuple; 6 | 7 | import com.cosium.synapse_junit_extension.EnableSynapse; 8 | import com.cosium.synapse_junit_extension.Synapse; 9 | import java.util.List; 10 | import java.util.UUID; 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.DisplayName; 13 | import org.junit.jupiter.api.Test; 14 | 15 | /** 16 | * @author Réda Housni Alaoui 17 | */ 18 | @EnableSynapse 19 | class RoomResourceTest { 20 | 21 | private MatrixResources resources; 22 | 23 | @BeforeEach 24 | void beforeEach(Synapse synapse) { 25 | resources = 26 | MatrixResources.factory() 27 | .builder() 28 | .https(synapse.https()) 29 | .hostname(synapse.hostname()) 30 | .port(synapse.port()) 31 | .usernamePassword(synapse.adminUsername(), synapse.adminPassword()) 32 | .build(); 33 | } 34 | 35 | @Test 36 | @DisplayName("Create room") 37 | void test1() { 38 | assertThatCode(this::createRoom).doesNotThrowAnyException(); 39 | } 40 | 41 | @Test 42 | @DisplayName("Send message to room") 43 | void test2() { 44 | Message message = Message.builder().body("body").formattedBody("formattedBody").build(); 45 | Message fetchedMessage = createRoom().sendMessage(message).fetch().content(Message.class); 46 | 47 | assertThat(List.of(fetchedMessage)) 48 | .extracting(Message::body, Message::format, Message::formattedBody, Message::type) 49 | .containsExactly( 50 | tuple(message.body(), message.format(), message.formattedBody(), message.type())); 51 | } 52 | 53 | @Test 54 | @DisplayName("Fetch event page") 55 | void test3() { 56 | Message message = Message.builder().body("body").formattedBody("formattedBody").build(); 57 | RoomResource room = createRoom(); 58 | room.sendMessage(message); 59 | 60 | ClientEventPage eventPage = room.fetchEventPage(null, null, null, null); 61 | List fetchedEvents = eventPage.chunk(); 62 | assertThat(fetchedEvents) 63 | .filteredOn(clientEvent -> "m.room.message".equals(clientEvent.type())) 64 | .map(clientEvent -> clientEvent.content(Message.class)) 65 | .extracting(Message::body, Message::format, Message::formattedBody, Message::type) 66 | .containsExactly( 67 | tuple(message.body(), message.format(), message.formattedBody(), message.type())); 68 | } 69 | 70 | private RoomResource createRoom() { 71 | CreateRoomInput createRoomInput = 72 | CreateRoomInput.builder() 73 | .name(UUID.randomUUID().toString()) 74 | .roomAliasName(UUID.randomUUID().toString()) 75 | .topic(UUID.randomUUID().toString()) 76 | .build(); 77 | return resources.rooms().create(createRoomInput); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/resources/META-INF/services/ch.qos.logback.classic.spi.Configurator: -------------------------------------------------------------------------------- 1 | com.cosium.matrix_communication_client.LogbackConfigurator 2 | -------------------------------------------------------------------------------- /src/test/resources/testcontainers.properties: -------------------------------------------------------------------------------- 1 | transport.type=httpclient5 2 | --------------------------------------------------------------------------------