├── .gitattributes ├── .github └── workflows │ ├── ci.yaml │ ├── codeql.yml │ ├── coveralls.yaml │ ├── site.yaml │ ├── sonar.yaml │ └── sonatype.yaml ├── .gitignore ├── .mvn ├── extensions.xml ├── maven.config ├── settings.xml └── wrapper │ ├── MavenWrapperDownloader.java │ └── maven-wrapper.properties ├── LICENSE ├── LICENSE_HEADER ├── NOTICE ├── README.md ├── format.xml ├── mvnw ├── mvnw.cmd ├── pom.xml ├── renovate.json └── src ├── main └── java │ └── org │ └── mybatis │ └── caches │ └── memcached │ ├── AbstractPropertySetter.java │ ├── BooleanPropertySetter.java │ ├── CompressorTranscoder.java │ ├── ConnectionFactorySetter.java │ ├── DummyReadWriteLock.java │ ├── InetSocketAddressListPropertySetter.java │ ├── IntegerPropertySetter.java │ ├── LoggingMemcachedCache.java │ ├── MemcachedCache.java │ ├── MemcachedClientWrapper.java │ ├── MemcachedConfiguration.java │ ├── MemcachedConfigurationBuilder.java │ ├── StringPropertySetter.java │ ├── StringUtils.java │ ├── TimeUnitSetter.java │ └── package-info.java ├── site ├── site.xml └── xdoc │ └── index.xml.vm └── test └── java └── org └── mybatis └── caches └── memcached ├── GroupTestThread.java └── MemcachedTestCase.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set. 2 | * text=auto -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [workflow_dispatch, push, pull_request] 4 | 5 | permissions: read-all 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | strategy: 11 | matrix: 12 | cache: [maven] 13 | distribution: [temurin] 14 | java: [17, 21, 24, 25-ea] 15 | os: [ubuntu-latest] 16 | fail-fast: false 17 | max-parallel: 4 18 | name: Test JDK ${{ matrix.java }}, ${{ matrix.os }} 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - uses: niden/actions-memcached@v7 23 | - name: Set up JDK ${{ matrix.java }} ${{ matrix.distribution }} 24 | uses: actions/setup-java@v4 25 | with: 26 | java-version: ${{ matrix.java }} 27 | distribution: ${{ matrix.distribution }} 28 | cache: ${{ matrix.cache }} 29 | - name: Test with Maven 30 | run: ./mvnw test -B -V --no-transfer-progress -D"license.skip=true" 31 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | schedule: 9 | - cron: '25 8 * * 6' 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} 15 | timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} 16 | permissions: 17 | actions: read 18 | contents: read 19 | security-events: write 20 | 21 | strategy: 22 | fail-fast: false 23 | matrix: 24 | language: [ 'java-kotlin' ] 25 | 26 | steps: 27 | - name: Checkout 28 | uses: actions/checkout@v4 29 | 30 | - name: Setup Java 31 | uses: actions/setup-java@v4 32 | with: 33 | cache: maven 34 | distribution: 'temurin' 35 | java-version: 21 36 | 37 | - name: Initialize CodeQL 38 | uses: github/codeql-action/init@v3 39 | with: 40 | languages: ${{ matrix.language }} 41 | queries: +security-and-quality 42 | 43 | - name: Autobuild 44 | uses: github/codeql-action/autobuild@v3 45 | 46 | - name: Perform CodeQL Analysis 47 | uses: github/codeql-action/analyze@v3 48 | with: 49 | category: "/language:${{ matrix.language }}" 50 | -------------------------------------------------------------------------------- /.github/workflows/coveralls.yaml: -------------------------------------------------------------------------------- 1 | name: Coveralls 2 | 3 | on: [push, pull_request] 4 | 5 | permissions: read-all 6 | 7 | jobs: 8 | build: 9 | if: github.repository_owner == 'mybatis' 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: niden/actions-memcached@v7 14 | - name: Set up JDK 15 | uses: actions/setup-java@v4 16 | with: 17 | cache: maven 18 | distribution: temurin 19 | java-version: 21 20 | - name: Report Coverage to Coveralls for Pull Requests 21 | if: github.event_name == 'pull_request' 22 | run: ./mvnw -B -V test jacoco:report coveralls:report -q -Dlicense.skip=true -DrepoToken=$GITHUB_TOKEN -DserviceName=github -DpullRequest=$PR_NUMBER --no-transfer-progress 23 | env: 24 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 25 | PR_NUMBER: ${{ github.event.number }} 26 | - name: Report Coverage to Coveralls for General Push 27 | if: github.event_name == 'push' 28 | run: ./mvnw -B -V test jacoco:report coveralls:report -q -Dlicense.skip=true -DrepoToken=$GITHUB_TOKEN -DserviceName=github --no-transfer-progress 29 | env: 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 31 | -------------------------------------------------------------------------------- /.github/workflows/site.yaml: -------------------------------------------------------------------------------- 1 | name: Site 2 | 3 | on: 4 | push: 5 | branches: 6 | - site 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | build: 13 | if: github.repository_owner == 'mybatis' && ! contains(toJSON(github.event.head_commit.message), '[maven-release-plugin]') 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Set up JDK 18 | uses: actions/setup-java@v4 19 | with: 20 | cache: maven 21 | distribution: temurin 22 | java-version: 21 23 | - name: Build site 24 | run: ./mvnw site site:stage -DskipTests -Dlicense.skip=true -B -V --no-transfer-progress --settings ./.mvn/settings.xml 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | NVD_API_KEY: ${{ secrets.NVD_API_KEY }} 28 | - name: Deploy Site to gh-pages 29 | uses: JamesIves/github-pages-deploy-action@v4 30 | with: 31 | branch: gh-pages 32 | folder: target/staging 33 | -------------------------------------------------------------------------------- /.github/workflows/sonar.yaml: -------------------------------------------------------------------------------- 1 | name: SonarCloud 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | permissions: read-all 9 | 10 | jobs: 11 | build: 12 | if: github.repository_owner == 'mybatis' 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | # Disabling shallow clone is recommended for improving relevancy of reporting 18 | fetch-depth: 0 19 | - uses: niden/actions-memcached@v7 20 | - name: Set up JDK 21 | uses: actions/setup-java@v4 22 | with: 23 | cache: maven 24 | distribution: temurin 25 | java-version: 21 26 | - name: Analyze with SonarCloud 27 | run: ./mvnw verify jacoco:report sonar:sonar -B -V -Dsonar.projectKey=mybatis_memcached-cache -Dsonar.organization=mybatis -Dsonar.host.url=https://sonarcloud.io -Dsonar.token=$SONAR_TOKEN -Dlicense.skip=true --no-transfer-progress 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 31 | -------------------------------------------------------------------------------- /.github/workflows/sonatype.yaml: -------------------------------------------------------------------------------- 1 | name: Sonatype 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | permissions: read-all 9 | 10 | jobs: 11 | build: 12 | if: github.repository_owner == 'mybatis' && ! contains(toJSON(github.event.head_commit.message), '[maven-release-plugin]') 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: niden/actions-memcached@v7 17 | - name: Set up JDK 18 | uses: actions/setup-java@v4 19 | with: 20 | cache: maven 21 | distribution: temurin 22 | java-version: 21 23 | - name: Deploy to Sonatype 24 | run: ./mvnw deploy -DskipTests -B -V --no-transfer-progress --settings ./.mvn/settings.xml -Dlicense.skip=true 25 | env: 26 | CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} 27 | CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /*.iml 2 | /*.ipr 3 | /*.iws 4 | /.classpath 5 | /.idea 6 | /.project 7 | /.settings 8 | /derby.log 9 | /ibderby 10 | /nb* 11 | /release.properties 12 | /target 13 | /test.db.lck 14 | /test.db.log 15 | /test.db.properties 16 | /test.db.script 17 | /test.db.tmp 18 | /src/docbkx 19 | velocity.log 20 | /bin 21 | .mvn/wrapper/maven-wrapper.jar 22 | *.releaseBackup 23 | -------------------------------------------------------------------------------- /.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | fr.jcgay.maven 22 | maven-profiler 23 | 3.3 24 | 25 | 26 | -------------------------------------------------------------------------------- /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | -Daether.checksums.algorithms=SHA-512,SHA-256,SHA-1,MD5 2 | -Daether.connector.smartChecksums=false 3 | -------------------------------------------------------------------------------- /.mvn/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 21 | 22 | 23 | 24 | 25 | central 26 | ${env.CI_DEPLOY_USERNAME} 27 | ${env.CI_DEPLOY_PASSWORD} 28 | 29 | 30 | 31 | 32 | gh-pages-scm 33 | 34 | branch 35 | gh-pages 36 | 37 | 38 | 39 | 40 | 41 | github 42 | ${env.GITHUB_TOKEN} 43 | 44 | 45 | 46 | 47 | nvd 48 | ${env.NVD_API_KEY} 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * https://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.net.Authenticator; 23 | import java.net.PasswordAuthentication; 24 | import java.net.URI; 25 | import java.net.URL; 26 | import java.nio.file.Files; 27 | import java.nio.file.Path; 28 | import java.nio.file.Paths; 29 | import java.nio.file.StandardCopyOption; 30 | import java.util.concurrent.ThreadLocalRandom; 31 | 32 | public final class MavenWrapperDownloader { 33 | private static final String WRAPPER_VERSION = "3.3.2"; 34 | 35 | private static final boolean VERBOSE = Boolean.parseBoolean(System.getenv("MVNW_VERBOSE")); 36 | 37 | public static void main(String[] args) { 38 | log("Apache Maven Wrapper Downloader " + WRAPPER_VERSION); 39 | 40 | if (args.length != 2) { 41 | System.err.println(" - ERROR wrapperUrl or wrapperJarPath parameter missing"); 42 | System.exit(1); 43 | } 44 | 45 | try { 46 | log(" - Downloader started"); 47 | final URL wrapperUrl = URI.create(args[0]).toURL(); 48 | final String jarPath = args[1].replace("..", ""); // Sanitize path 49 | final Path wrapperJarPath = Paths.get(jarPath).toAbsolutePath().normalize(); 50 | downloadFileFromURL(wrapperUrl, wrapperJarPath); 51 | log("Done"); 52 | } catch (IOException e) { 53 | System.err.println("- Error downloading: " + e.getMessage()); 54 | if (VERBOSE) { 55 | e.printStackTrace(); 56 | } 57 | System.exit(1); 58 | } 59 | } 60 | 61 | private static void downloadFileFromURL(URL wrapperUrl, Path wrapperJarPath) 62 | throws IOException { 63 | log(" - Downloading to: " + wrapperJarPath); 64 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 65 | final String username = System.getenv("MVNW_USERNAME"); 66 | final char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 67 | Authenticator.setDefault(new Authenticator() { 68 | @Override 69 | protected PasswordAuthentication getPasswordAuthentication() { 70 | return new PasswordAuthentication(username, password); 71 | } 72 | }); 73 | } 74 | Path temp = wrapperJarPath 75 | .getParent() 76 | .resolve(wrapperJarPath.getFileName() + "." 77 | + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp"); 78 | try (InputStream inStream = wrapperUrl.openStream()) { 79 | Files.copy(inStream, temp, StandardCopyOption.REPLACE_EXISTING); 80 | Files.move(temp, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING); 81 | } finally { 82 | Files.deleteIfExists(temp); 83 | } 84 | log(" - Downloader complete"); 85 | } 86 | 87 | private static void log(String msg) { 88 | if (VERBOSE) { 89 | System.out.println(msg); 90 | } 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /.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 | wrapperVersion=3.3.2 18 | distributionType=source 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip 20 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | https://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE_HEADER: -------------------------------------------------------------------------------- 1 | Copyright ${license.git.copyrightYears} the original author or authors. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | MyBatis-Memcached cache 2 | Copyright 2010-2023 3 | 4 | This product includes software developed by 5 | The MyBatis Team (http://mybatis.org/). 6 | 7 | This product includes software developed by 8 | Dustin Sullins (http://code.google.com/p/spymemcached/) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MyBatis Memcached Extension 2 | =========================== 3 | 4 | [![Java CI](https://github.com/mybatis/memcached-cache/actions/workflows/ci.yaml/badge.svg)](https://github.com/mybatis/memcached-cache/actions/workflows/ci.yaml) 5 | [![Coverage Status](https://coveralls.io/repos/mybatis/memcached-cache/badge.svg?branch=master&service=github)](https://coveralls.io/github/mybatis/memcached-cache?branch=master) 6 | [![Maven central](https://maven-badges.herokuapp.com/maven-central/org.mybatis.caches/mybatis-memcached/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.mybatis.caches/mybatis-memcached) 7 | [![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/https/oss.sonatype.org/org.mybatis.caches/mybatis-memcached.svg)](https://oss.sonatype.org/content/repositories/snapshots/org/mybatis/caches/mybatis-memcached/) 8 | [![License](https://img.shields.io/:license-apache-brightgreen.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) 9 | 10 | ![mybatis-memcached](https://mybatis.org/images/mybatis-logo.png) 11 | 12 | MyBatis-Memcached extension Memcached support for MyBatis Cache. 13 | 14 | Essentials 15 | ---------- 16 | 17 | * [See the docs](https://mybatis.org/memcached-cache/) 18 | 19 | Releasing 20 | --------- 21 | 22 | To release this library, use the maven release plugin. If no memcache installed ensure to set the following profile ```-PnoTest```. 23 | 24 | Typical maven release is done as follows where tests ignored. 25 | 26 | mvn release:clean 27 | mvn release:prepare -PnoTest 28 | mvn release:perform -PnoTest 29 | -------------------------------------------------------------------------------- /format.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /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 | # https://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 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | # e.g. to debug Maven itself, use 32 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | # ---------------------------------------------------------------------------- 35 | 36 | if [ -z "$MAVEN_SKIP_RC" ]; then 37 | 38 | if [ -f /usr/local/etc/mavenrc ]; then 39 | . /usr/local/etc/mavenrc 40 | fi 41 | 42 | if [ -f /etc/mavenrc ]; then 43 | . /etc/mavenrc 44 | fi 45 | 46 | if [ -f "$HOME/.mavenrc" ]; then 47 | . "$HOME/.mavenrc" 48 | fi 49 | 50 | fi 51 | 52 | # OS specific support. $var _must_ be set to either true or false. 53 | cygwin=false 54 | darwin=false 55 | mingw=false 56 | case "$(uname)" in 57 | CYGWIN*) cygwin=true ;; 58 | MINGW*) mingw=true ;; 59 | Darwin*) 60 | darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | JAVA_HOME="$(/usr/libexec/java_home)" 66 | export JAVA_HOME 67 | else 68 | JAVA_HOME="/Library/Java/Home" 69 | export JAVA_HOME 70 | fi 71 | fi 72 | ;; 73 | esac 74 | 75 | if [ -z "$JAVA_HOME" ]; then 76 | if [ -r /etc/gentoo-release ]; then 77 | JAVA_HOME=$(java-config --jre-home) 78 | fi 79 | fi 80 | 81 | # For Cygwin, ensure paths are in UNIX format before anything is touched 82 | if $cygwin; then 83 | [ -n "$JAVA_HOME" ] \ 84 | && JAVA_HOME=$(cygpath --unix "$JAVA_HOME") 85 | [ -n "$CLASSPATH" ] \ 86 | && CLASSPATH=$(cygpath --path --unix "$CLASSPATH") 87 | fi 88 | 89 | # For Mingw, ensure paths are in UNIX format before anything is touched 90 | if $mingw; then 91 | [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] \ 92 | && JAVA_HOME="$( 93 | cd "$JAVA_HOME" || ( 94 | echo "cannot cd into $JAVA_HOME." >&2 95 | exit 1 96 | ) 97 | pwd 98 | )" 99 | fi 100 | 101 | if [ -z "$JAVA_HOME" ]; then 102 | javaExecutable="$(which javac)" 103 | if [ -n "$javaExecutable" ] && ! [ "$(expr "$javaExecutable" : '\([^ ]*\)')" = "no" ]; then 104 | # readlink(1) is not available as standard on Solaris 10. 105 | readLink=$(which readlink) 106 | if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then 107 | if $darwin; then 108 | javaHome="$(dirname "$javaExecutable")" 109 | javaExecutable="$(cd "$javaHome" && pwd -P)/javac" 110 | else 111 | javaExecutable="$(readlink -f "$javaExecutable")" 112 | fi 113 | javaHome="$(dirname "$javaExecutable")" 114 | javaHome=$(expr "$javaHome" : '\(.*\)/bin') 115 | JAVA_HOME="$javaHome" 116 | export JAVA_HOME 117 | fi 118 | fi 119 | fi 120 | 121 | if [ -z "$JAVACMD" ]; then 122 | if [ -n "$JAVA_HOME" ]; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD="$JAVA_HOME/jre/sh/java" 126 | else 127 | JAVACMD="$JAVA_HOME/bin/java" 128 | fi 129 | else 130 | JAVACMD="$( 131 | \unset -f command 2>/dev/null 132 | \command -v java 133 | )" 134 | fi 135 | fi 136 | 137 | if [ ! -x "$JAVACMD" ]; then 138 | echo "Error: JAVA_HOME is not defined correctly." >&2 139 | echo " We cannot execute $JAVACMD" >&2 140 | exit 1 141 | fi 142 | 143 | if [ -z "$JAVA_HOME" ]; then 144 | echo "Warning: JAVA_HOME environment variable is not set." >&2 145 | fi 146 | 147 | # traverses directory structure from process work directory to filesystem root 148 | # first directory with .mvn subdirectory is considered project base directory 149 | find_maven_basedir() { 150 | if [ -z "$1" ]; then 151 | echo "Path not specified to find_maven_basedir" >&2 152 | return 1 153 | fi 154 | 155 | basedir="$1" 156 | wdir="$1" 157 | while [ "$wdir" != '/' ]; do 158 | if [ -d "$wdir"/.mvn ]; then 159 | basedir=$wdir 160 | break 161 | fi 162 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 163 | if [ -d "${wdir}" ]; then 164 | wdir=$( 165 | cd "$wdir/.." || exit 1 166 | pwd 167 | ) 168 | fi 169 | # end of workaround 170 | done 171 | printf '%s' "$( 172 | cd "$basedir" || exit 1 173 | pwd 174 | )" 175 | } 176 | 177 | # concatenates all lines of a file 178 | concat_lines() { 179 | if [ -f "$1" ]; then 180 | # Remove \r in case we run on Windows within Git Bash 181 | # and check out the repository with auto CRLF management 182 | # enabled. Otherwise, we may read lines that are delimited with 183 | # \r\n and produce $'-Xarg\r' rather than -Xarg due to word 184 | # splitting rules. 185 | tr -s '\r\n' ' ' <"$1" 186 | fi 187 | } 188 | 189 | log() { 190 | if [ "$MVNW_VERBOSE" = true ]; then 191 | printf '%s\n' "$1" 192 | fi 193 | } 194 | 195 | BASE_DIR=$(find_maven_basedir "$(dirname "$0")") 196 | if [ -z "$BASE_DIR" ]; then 197 | exit 1 198 | fi 199 | 200 | MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 201 | export MAVEN_PROJECTBASEDIR 202 | log "$MAVEN_PROJECTBASEDIR" 203 | 204 | ########################################################################################## 205 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 206 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 207 | ########################################################################################## 208 | wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" 209 | if [ -r "$wrapperJarPath" ]; then 210 | log "Found $wrapperJarPath" 211 | else 212 | log "Couldn't find $wrapperJarPath, downloading it ..." 213 | 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" 216 | else 217 | wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" 218 | fi 219 | while IFS="=" read -r key value; do 220 | # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) 221 | safeValue=$(echo "$value" | tr -d '\r') 222 | case "$key" in wrapperUrl) 223 | wrapperUrl="$safeValue" 224 | break 225 | ;; 226 | esac 227 | done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 228 | log "Downloading from: $wrapperUrl" 229 | 230 | if $cygwin; then 231 | wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") 232 | fi 233 | 234 | if command -v wget >/dev/null; then 235 | log "Found wget ... using wget" 236 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" 237 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 238 | wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 239 | else 240 | wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | fi 242 | elif command -v curl >/dev/null; then 243 | log "Found curl ... using curl" 244 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" 245 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 246 | curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 247 | else 248 | curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 249 | fi 250 | else 251 | log "Falling back to using Java to download" 252 | javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" 253 | javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" 254 | # For Cygwin, switch paths to Windows format before running javac 255 | if $cygwin; then 256 | javaSource=$(cygpath --path --windows "$javaSource") 257 | javaClass=$(cygpath --path --windows "$javaClass") 258 | fi 259 | if [ -e "$javaSource" ]; then 260 | if [ ! -e "$javaClass" ]; then 261 | log " - Compiling MavenWrapperDownloader.java ..." 262 | ("$JAVA_HOME/bin/javac" "$javaSource") 263 | fi 264 | if [ -e "$javaClass" ]; then 265 | log " - Running MavenWrapperDownloader.java ..." 266 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" 267 | fi 268 | fi 269 | fi 270 | fi 271 | ########################################################################################## 272 | # End of extension 273 | ########################################################################################## 274 | 275 | # If specified, validate the SHA-256 sum of the Maven wrapper jar file 276 | wrapperSha256Sum="" 277 | while IFS="=" read -r key value; do 278 | case "$key" in wrapperSha256Sum) 279 | wrapperSha256Sum=$value 280 | break 281 | ;; 282 | esac 283 | done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 284 | if [ -n "$wrapperSha256Sum" ]; then 285 | wrapperSha256Result=false 286 | if command -v sha256sum >/dev/null; then 287 | if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c >/dev/null 2>&1; then 288 | wrapperSha256Result=true 289 | fi 290 | elif command -v shasum >/dev/null; then 291 | if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c >/dev/null 2>&1; then 292 | wrapperSha256Result=true 293 | fi 294 | else 295 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 296 | echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." >&2 297 | exit 1 298 | fi 299 | if [ $wrapperSha256Result = false ]; then 300 | echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 301 | echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 302 | echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 303 | exit 1 304 | fi 305 | fi 306 | 307 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 308 | 309 | # For Cygwin, switch paths to Windows format before running java 310 | if $cygwin; then 311 | [ -n "$JAVA_HOME" ] \ 312 | && JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") 313 | [ -n "$CLASSPATH" ] \ 314 | && CLASSPATH=$(cygpath --path --windows "$CLASSPATH") 315 | [ -n "$MAVEN_PROJECTBASEDIR" ] \ 316 | && MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") 317 | fi 318 | 319 | # Provide a "standardized" way to retrieve the CLI args that will 320 | # work with both Windows and non-Windows executions. 321 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" 322 | export MAVEN_CMD_LINE_ARGS 323 | 324 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 325 | 326 | # shellcheck disable=SC2086 # safe args 327 | exec "$JAVACMD" \ 328 | $MAVEN_OPTS \ 329 | $MAVEN_DEBUG_OPTS \ 330 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 331 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 332 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 333 | -------------------------------------------------------------------------------- /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 https://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 Apache Maven Wrapper startup batch script, version 3.3.2 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 MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 28 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 29 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 30 | @REM e.g. to debug Maven itself, use 31 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 32 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 33 | @REM ---------------------------------------------------------------------------- 34 | 35 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 36 | @echo off 37 | @REM set title of command window 38 | title %0 39 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 40 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 41 | 42 | @REM set %HOME% to equivalent of $HOME 43 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 44 | 45 | @REM Execute a user defined script before this one 46 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 47 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 48 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 49 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 50 | :skipRcPre 51 | 52 | @setlocal 53 | 54 | set ERROR_CODE=0 55 | 56 | @REM To isolate internal variables from possible post scripts, we use another setlocal 57 | @setlocal 58 | 59 | @REM ==== START VALIDATION ==== 60 | if not "%JAVA_HOME%" == "" goto OkJHome 61 | 62 | echo. >&2 63 | echo Error: JAVA_HOME not found in your environment. >&2 64 | echo Please set the JAVA_HOME variable in your environment to match the >&2 65 | echo location of your Java installation. >&2 66 | echo. >&2 67 | goto error 68 | 69 | :OkJHome 70 | if exist "%JAVA_HOME%\bin\java.exe" goto init 71 | 72 | echo. >&2 73 | echo Error: JAVA_HOME is set to an invalid directory. >&2 74 | echo JAVA_HOME = "%JAVA_HOME%" >&2 75 | echo Please set the JAVA_HOME variable in your environment to match the >&2 76 | echo location of your Java installation. >&2 77 | echo. >&2 78 | goto error 79 | 80 | @REM ==== END VALIDATION ==== 81 | 82 | :init 83 | 84 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 85 | @REM Fallback to current working directory if not found. 86 | 87 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 88 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 89 | 90 | set EXEC_DIR=%CD% 91 | set WDIR=%EXEC_DIR% 92 | :findBaseDir 93 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 94 | cd .. 95 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 96 | set WDIR=%CD% 97 | goto findBaseDir 98 | 99 | :baseDirFound 100 | set MAVEN_PROJECTBASEDIR=%WDIR% 101 | cd "%EXEC_DIR%" 102 | goto endDetectBaseDir 103 | 104 | :baseDirNotFound 105 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 106 | cd "%EXEC_DIR%" 107 | 108 | :endDetectBaseDir 109 | 110 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 111 | 112 | @setlocal EnableExtensions EnableDelayedExpansion 113 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 114 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 115 | 116 | :endReadAdditionalConfig 117 | 118 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" 123 | 124 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 125 | IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | if "%MVNW_VERBOSE%" == "true" ( 132 | echo Found %WRAPPER_JAR% 133 | ) 134 | ) else ( 135 | if not "%MVNW_REPOURL%" == "" ( 136 | SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar" 137 | ) 138 | if "%MVNW_VERBOSE%" == "true" ( 139 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 140 | echo Downloading from: %WRAPPER_URL% 141 | ) 142 | 143 | powershell -Command "&{"^ 144 | "$webclient = new-object System.Net.WebClient;"^ 145 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 146 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 147 | "}"^ 148 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ 149 | "}" 150 | if "%MVNW_VERBOSE%" == "true" ( 151 | echo Finished downloading %WRAPPER_JAR% 152 | ) 153 | ) 154 | @REM End of extension 155 | 156 | @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file 157 | SET WRAPPER_SHA_256_SUM="" 158 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 159 | IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B 160 | ) 161 | IF NOT %WRAPPER_SHA_256_SUM%=="" ( 162 | powershell -Command "&{"^ 163 | "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ 164 | "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ 165 | "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ 166 | " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ 167 | " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ 168 | " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ 169 | " exit 1;"^ 170 | "}"^ 171 | "}" 172 | if ERRORLEVEL 1 goto error 173 | ) 174 | 175 | @REM Provide a "standardized" way to retrieve the CLI args that will 176 | @REM work with both Windows and non-Windows executions. 177 | set MAVEN_CMD_LINE_ARGS=%* 178 | 179 | %MAVEN_JAVA_EXE% ^ 180 | %JVM_CONFIG_MAVEN_PROPS% ^ 181 | %MAVEN_OPTS% ^ 182 | %MAVEN_DEBUG_OPTS% ^ 183 | -classpath %WRAPPER_JAR% ^ 184 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 185 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 186 | if ERRORLEVEL 1 goto error 187 | goto end 188 | 189 | :error 190 | set ERROR_CODE=1 191 | 192 | :end 193 | @endlocal & set ERROR_CODE=%ERROR_CODE% 194 | 195 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 196 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 197 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 198 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 199 | :skipRcPost 200 | 201 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 202 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 203 | 204 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 205 | 206 | cmd /C exit /B %ERROR_CODE% 207 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 4.0.0 21 | 22 | 23 | org.mybatis 24 | mybatis-parent 25 | 50 26 | 27 | 28 | 29 | org.mybatis.caches 30 | mybatis-memcached 31 | 1.1.2-SNAPSHOT 32 | 33 | mybatis-memcached 34 | Memcached support for MyBatis Cache 35 | https://www.mybatis.org/memcached-cache/ 36 | 37 | 2012 38 | 39 | 40 | scm:git:ssh://git@github.com/mybatis/memcached-cache.git 41 | scm:git:ssh://git@github.com/mybatis/memcached-cache.git 42 | HEAD 43 | http://github.com/mybatis/memcached-cache/ 44 | 45 | 46 | GitHub Issue Management 47 | https://github.com/mybatis/memcached-cache/issues 48 | 49 | 50 | GitHub Actions 51 | https://github.com/mybatis/memcached-cache/actions 52 | 53 | 54 | 55 | gh-pages-scm 56 | Mybatis GitHub Pages 57 | scm:git:ssh://git@github.com/mybatis/memcached-cache.git 58 | 59 | 60 | 61 | 62 | 1.0.0 63 | org.mybatis.caches.memcached.* 64 | Cache 65 | org.mybatis.caches.memcached 66 | -Djdk.attach.allowAttachSelf -Xms1024m -Xmx1024m 67 | 68 | 69 | 1670887830 70 | 71 | 72 | 73 | 74 | 75 | org.mybatis 76 | mybatis 77 | 3.5.19 78 | provided 79 | 80 | 81 | 82 | 83 | net.spy 84 | spymemcached 85 | 2.12.3 86 | compile 87 | 88 | 89 | 90 | 91 | org.junit.jupiter 92 | junit-jupiter-engine 93 | 5.13.0 94 | test 95 | 96 | 97 | 98 | 99 | 100 | 101 | org.apache.maven.plugins 102 | maven-release-plugin 103 | 104 | release,bundle 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | noTest 114 | 115 | 116 | noTest 117 | true 118 | 119 | 120 | 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-surefire-plugin 125 | 126 | true 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/AbstractPropertySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.beans.BeanInfo; 19 | import java.beans.IntrospectionException; 20 | import java.beans.Introspector; 21 | import java.beans.PropertyDescriptor; 22 | import java.lang.reflect.Method; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | import java.util.Properties; 26 | 27 | /** 28 | * Converts a keyed property string in the Config to a proper Java object representation. 29 | * 30 | * @author Simone Tripodi 31 | */ 32 | abstract class AbstractPropertySetter { 33 | 34 | /** 35 | * 'propertyName'='writermethod' index of {@link MemcachedConfiguration} properties. 36 | */ 37 | private static Map WRITERS = new HashMap(); 38 | 39 | static { 40 | try { 41 | BeanInfo memcachedConfigInfo = Introspector.getBeanInfo(MemcachedConfiguration.class); 42 | for (PropertyDescriptor descriptor : memcachedConfigInfo.getPropertyDescriptors()) { 43 | WRITERS.put(descriptor.getName(), descriptor.getWriteMethod()); 44 | } 45 | } catch (IntrospectionException e) { 46 | // handle quietly 47 | } 48 | } 49 | 50 | /** 51 | * The Config property key. 52 | */ 53 | private final String propertyKey; 54 | 55 | /** 56 | * The {@link MemcachedConfiguration} property name. 57 | */ 58 | private final String propertyName; 59 | 60 | /** 61 | * The {@link MemcachedConfiguration} property method writer. 62 | */ 63 | private final Method propertyWriterMethod; 64 | 65 | /** 66 | * The default value used if something goes wrong during the conversion or the property is not set in the config. 67 | */ 68 | private final T defaultValue; 69 | 70 | /** 71 | * Build a new property setter. 72 | * 73 | * @param propertyKey 74 | * the Config property key. 75 | * @param propertyName 76 | * the {@link MemcachedConfiguration} property name. 77 | * @param defaultValue 78 | * the property default value. 79 | */ 80 | public AbstractPropertySetter(final String propertyKey, final String propertyName, final T defaultValue) { 81 | this.propertyKey = propertyKey; 82 | this.propertyName = propertyName; 83 | 84 | this.propertyWriterMethod = WRITERS.get(propertyName); 85 | if (this.propertyWriterMethod == null) { 86 | throw new RuntimeException( 87 | "Class '" + MemcachedConfiguration.class.getName() + "' doesn't contain a property '" + propertyName + "'"); 88 | } 89 | 90 | this.defaultValue = defaultValue; 91 | } 92 | 93 | /** 94 | * Extract a property from the, converts and puts it to the {@link MemcachedConfiguration}. 95 | * 96 | * @param config 97 | * the Config 98 | * @param memcachedConfiguration 99 | * the {@link MemcachedConfiguration} 100 | */ 101 | public final void set(Properties config, MemcachedConfiguration memcachedConfiguration) { 102 | String propertyValue = config.getProperty(propertyKey); 103 | T value; 104 | 105 | try { 106 | value = this.convert(propertyValue); 107 | if (value == null) { 108 | value = defaultValue; 109 | } 110 | } catch (Exception e) { 111 | value = defaultValue; 112 | } 113 | 114 | try { 115 | propertyWriterMethod.invoke(memcachedConfiguration, value); 116 | } catch (Exception e) { 117 | throw new RuntimeException("Impossible to set property '" + propertyName + "' with value '" + value 118 | + "', extracted from ('" + propertyKey + "'=" + propertyValue + ")", e); 119 | } 120 | } 121 | 122 | /** 123 | * Convert a string representation to a proper Java Object. 124 | * 125 | * @param value 126 | * the value has to be converted. 127 | * 128 | * @return the converted value. 129 | * 130 | * @throws Exception 131 | * if any error occurs. 132 | */ 133 | protected abstract T convert(String value) throws Exception; 134 | 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/BooleanPropertySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | /** 19 | * Setter from String to Boolean representation. 20 | * 21 | * @author Simone Tripodi 22 | */ 23 | final class BooleanPropertySetter extends AbstractPropertySetter { 24 | 25 | /** 26 | * Instantiates a String to Boolean setter. 27 | * 28 | * @param propertyKey 29 | * the OSCache Config property key. 30 | * @param propertyName 31 | * the {@link MemcachedConfiguration} property name. 32 | * @param defaultValue 33 | * the property default value. 34 | */ 35 | public BooleanPropertySetter(final String propertyKey, final String propertyName, final Boolean defaultValue) { 36 | super(propertyKey, propertyName, defaultValue); 37 | } 38 | 39 | /** 40 | * {@inheritDoc} 41 | */ 42 | @Override 43 | protected Boolean convert(String property) throws Exception { 44 | return Boolean.valueOf(property); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/CompressorTranscoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.io.ByteArrayInputStream; 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.Closeable; 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.io.ObjectInputStream; 24 | import java.io.ObjectOutputStream; 25 | import java.util.zip.GZIPInputStream; 26 | import java.util.zip.GZIPOutputStream; 27 | 28 | import net.spy.memcached.CachedData; 29 | import net.spy.memcached.transcoders.Transcoder; 30 | 31 | import org.apache.ibatis.cache.CacheException; 32 | 33 | /** 34 | * The Transcoder that compress and decompress the stored objects using the GZIP compression algorithm. 35 | * 36 | * @author Simone Tripodi 37 | */ 38 | final class CompressorTranscoder implements Transcoder { 39 | 40 | /** 41 | * The serialized and compressed flag. 42 | */ 43 | private static final int SERIALIZED_COMPRESSED = 3; 44 | 45 | /** 46 | * {@inheritDoc} 47 | */ 48 | @Override 49 | public boolean asyncDecode(final CachedData cachedData) { 50 | return false; 51 | } 52 | 53 | /** 54 | * {@inheritDoc} 55 | */ 56 | @Override 57 | public Object decode(final CachedData cachedData) { 58 | byte[] buffer = cachedData.getData(); 59 | 60 | ByteArrayInputStream bais = new ByteArrayInputStream(buffer); 61 | GZIPInputStream gzis = null; 62 | ObjectInputStream ois = null; 63 | Object ret = null; 64 | 65 | try { 66 | gzis = new GZIPInputStream(bais); 67 | ois = new ObjectInputStream(gzis); 68 | ret = ois.readObject(); 69 | } catch (Exception e) { 70 | throw new CacheException("Impossible to decompress cached object, see nested exceptions", e); 71 | } finally { 72 | closeQuietly(ois); 73 | closeQuietly(gzis); 74 | closeQuietly(bais); 75 | } 76 | return ret; 77 | } 78 | 79 | /** 80 | * {@inheritDoc} 81 | */ 82 | @Override 83 | public CachedData encode(final Object object) { 84 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 85 | GZIPOutputStream gzops = null; 86 | ObjectOutputStream oos = null; 87 | 88 | try { 89 | gzops = new GZIPOutputStream(baos); 90 | oos = new ObjectOutputStream(gzops); 91 | oos.writeObject(object); 92 | } catch (IOException e) { 93 | throw new CacheException("Impossible to compress object [" + object + "], see nested exceptions", e); 94 | } finally { 95 | closeQuietly(oos); 96 | closeQuietly(gzops); 97 | closeQuietly(baos); 98 | } 99 | 100 | byte[] buffer = baos.toByteArray(); 101 | return new CachedData(SERIALIZED_COMPRESSED, buffer, CachedData.MAX_SIZE); 102 | } 103 | 104 | /** 105 | * {@inheritDoc} 106 | */ 107 | @Override 108 | public int getMaxSize() { 109 | return Integer.MAX_VALUE; 110 | } 111 | 112 | /** 113 | * Unconditionally close an {@link InputStream}. 114 | * 115 | * @param closeable 116 | * the InputStream to close, may be null or already closed. 117 | */ 118 | private static void closeQuietly(final Closeable closeable) { 119 | if (closeable != null) { 120 | try { 121 | closeable.close(); 122 | } catch (IOException e) { 123 | // do nothing 124 | } 125 | } 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/ConnectionFactorySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import net.spy.memcached.ConnectionFactory; 19 | import net.spy.memcached.DefaultConnectionFactory; 20 | 21 | /** 22 | * Setter from String to ConnectionFactory representation. 23 | * 24 | * @author Simone Tripodi 25 | */ 26 | final class ConnectionFactorySetter extends AbstractPropertySetter { 27 | 28 | /** 29 | * Instantiates a String to ConnectionFactory setter. 30 | */ 31 | public ConnectionFactorySetter() { 32 | super("org.mybatis.caches.memcached.connectionfactory", "connectionFactory", new DefaultConnectionFactory()); 33 | } 34 | 35 | /** 36 | * {@inheritDoc} 37 | */ 38 | @Override 39 | protected ConnectionFactory convert(String property) throws Exception { 40 | Class clazz = Class.forName(property); 41 | if (!ConnectionFactory.class.isAssignableFrom(clazz)) { 42 | throw new IllegalArgumentException( 43 | "Class '" + clazz.getName() + "' is not a valid '" + ConnectionFactory.class.getName() + "' implementation"); 44 | } 45 | return (ConnectionFactory) clazz.newInstance(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/DummyReadWriteLock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.locks.Condition; 20 | import java.util.concurrent.locks.Lock; 21 | import java.util.concurrent.locks.ReadWriteLock; 22 | 23 | /** 24 | * @author Iwao AVE! 25 | */ 26 | class DummyReadWriteLock implements ReadWriteLock { 27 | 28 | private Lock lock = new DummyLock(); 29 | 30 | @Override 31 | public Lock readLock() { 32 | return lock; 33 | } 34 | 35 | @Override 36 | public Lock writeLock() { 37 | return lock; 38 | } 39 | 40 | static class DummyLock implements Lock { 41 | 42 | @Override 43 | public void lock() { 44 | // Not Implemented 45 | } 46 | 47 | @Override 48 | public void lockInterruptibly() throws InterruptedException { 49 | // Not Implemented 50 | } 51 | 52 | @Override 53 | public boolean tryLock() { 54 | return true; 55 | } 56 | 57 | @Override 58 | public boolean tryLock(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException { 59 | return true; 60 | } 61 | 62 | @Override 63 | public void unlock() { 64 | // Not Implemented 65 | } 66 | 67 | @Override 68 | public Condition newCondition() { 69 | return null; 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/InetSocketAddressListPropertySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.net.InetSocketAddress; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | import net.spy.memcached.AddrUtil; 23 | 24 | /** 25 | * Setter from String to list of InetSocketAddress representation. 26 | * 27 | * @author Simone Tripodi 28 | */ 29 | final class InetSocketAddressListPropertySetter extends AbstractPropertySetter> { 30 | 31 | private static final List SOCKET_LIST = Arrays.asList(new InetSocketAddress("localhost", 11211)); 32 | 33 | /** 34 | * Instantiates a String to List<InetSocketAddress> setter. 35 | */ 36 | public InetSocketAddressListPropertySetter() { 37 | super("org.mybatis.caches.memcached.servers", "addresses", SOCKET_LIST); 38 | } 39 | 40 | @Override 41 | protected List convert(String property) throws Exception { 42 | return AddrUtil.getAddresses(property); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/IntegerPropertySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | /** 19 | * Setter from String to Integer representation. 20 | * 21 | * @author Simone Tripodi 22 | */ 23 | final class IntegerPropertySetter extends AbstractPropertySetter { 24 | 25 | /** 26 | * Instantiates a String to Integer setter. 27 | * 28 | * @param propertyKey 29 | * the Config property key. 30 | * @param propertyName 31 | * the {@link MemcachedConfiguration} property name. 32 | * @param defaultValue 33 | * the property default value. 34 | */ 35 | public IntegerPropertySetter(final String propertyKey, final String propertyName, final Integer defaultValue) { 36 | super(propertyKey, propertyName, defaultValue); 37 | } 38 | 39 | /** 40 | * {@inheritDoc} 41 | */ 42 | @Override 43 | protected Integer convert(String property) throws Exception { 44 | return Integer.valueOf(property); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/LoggingMemcachedCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import org.apache.ibatis.cache.decorators.LoggingCache; 19 | 20 | /** 21 | * {@code LoggingCache} adapter for Memcached. 22 | * 23 | * @author Simone Tripodi 24 | */ 25 | public final class LoggingMemcachedCache extends LoggingCache { 26 | 27 | public LoggingMemcachedCache(final String id) { 28 | super(new MemcachedCache(id)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/MemcachedCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.util.concurrent.locks.ReadWriteLock; 19 | 20 | import org.apache.ibatis.cache.Cache; 21 | 22 | /** 23 | * The Memcached-based Cache implementation. 24 | * 25 | * @author Simone Tripodi 26 | */ 27 | public final class MemcachedCache implements Cache { 28 | 29 | private static final MemcachedClientWrapper MEMCACHED_CLIENT = new MemcachedClientWrapper(); 30 | 31 | /** 32 | * The {@link ReadWriteLock}. 33 | */ 34 | private final ReadWriteLock readWriteLock = new DummyReadWriteLock(); 35 | 36 | /** 37 | * The cache id. 38 | */ 39 | private final String id; 40 | 41 | /** 42 | * Builds a new Memcached-based Cache. 43 | * 44 | * @param id 45 | * the Mapper id. 46 | */ 47 | public MemcachedCache(final String id) { 48 | this.id = id; 49 | } 50 | 51 | /** 52 | * {@inheritDoc} 53 | */ 54 | @Override 55 | public void clear() { 56 | MEMCACHED_CLIENT.removeGroup(this.id); 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | */ 62 | @Override 63 | public String getId() { 64 | return this.id; 65 | } 66 | 67 | /** 68 | * {@inheritDoc} 69 | */ 70 | @Override 71 | public Object getObject(Object key) { 72 | return MEMCACHED_CLIENT.getObject(key); 73 | } 74 | 75 | /** 76 | * {@inheritDoc} 77 | */ 78 | @Override 79 | public ReadWriteLock getReadWriteLock() { 80 | return this.readWriteLock; 81 | } 82 | 83 | /** 84 | * {@inheritDoc} 85 | */ 86 | @Override 87 | public int getSize() { 88 | return Integer.MAX_VALUE; 89 | } 90 | 91 | /** 92 | * {@inheritDoc} 93 | */ 94 | @Override 95 | public void putObject(Object key, Object value) { 96 | MEMCACHED_CLIENT.putObject(key, value, this.id); 97 | } 98 | 99 | /** 100 | * {@inheritDoc} 101 | */ 102 | @Override 103 | public Object removeObject(Object key) { 104 | return MEMCACHED_CLIENT.removeObject(key); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/MemcachedClientWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.io.IOException; 19 | import java.io.Serializable; 20 | import java.util.HashSet; 21 | import java.util.Set; 22 | import java.util.concurrent.ExecutionException; 23 | import java.util.concurrent.Future; 24 | 25 | import net.spy.memcached.CASResponse; 26 | import net.spy.memcached.CASValue; 27 | import net.spy.memcached.ConnectionFactoryBuilder; 28 | import net.spy.memcached.MemcachedClient; 29 | import net.spy.memcached.auth.AuthDescriptor; 30 | import net.spy.memcached.auth.PlainCallbackHandler; 31 | import net.spy.memcached.internal.OperationFuture; 32 | 33 | import org.apache.ibatis.cache.CacheException; 34 | import org.apache.ibatis.logging.Log; 35 | import org.apache.ibatis.logging.LogFactory; 36 | 37 | /** 38 | * @author Simone Tripodi 39 | */ 40 | final class MemcachedClientWrapper { 41 | 42 | /** 43 | * This class log. 44 | */ 45 | private static final Log LOG = LogFactory.getLog(MemcachedCache.class); 46 | 47 | private final MemcachedConfiguration configuration; 48 | 49 | private final MemcachedClient client; 50 | 51 | /** 52 | * Used to represent an object retrieved from Memcached along with its CAS information 53 | * 54 | * @author Weisz, Gustavo E. 55 | */ 56 | private class ObjectWithCas { 57 | 58 | Object object; 59 | long cas; 60 | 61 | ObjectWithCas(Object object, long cas) { 62 | this.setObject(object); 63 | this.setCas(cas); 64 | } 65 | 66 | public Object getObject() { 67 | return object; 68 | } 69 | 70 | public void setObject(Object object) { 71 | this.object = object; 72 | } 73 | 74 | public long getCas() { 75 | return cas; 76 | } 77 | 78 | public void setCas(long cas) { 79 | this.cas = cas; 80 | } 81 | 82 | } 83 | 84 | public MemcachedClientWrapper() { 85 | configuration = MemcachedConfigurationBuilder.getInstance().parseConfiguration(); 86 | try { 87 | if (configuration.isUsingSASL()) { 88 | AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" }, 89 | new PlainCallbackHandler(configuration.getUsername(), configuration.getPassword())); 90 | client = new MemcachedClient(new ConnectionFactoryBuilder() 91 | .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY).setAuthDescriptor(ad).build(), 92 | configuration.getAddresses()); 93 | } else { 94 | client = new MemcachedClient(configuration.getConnectionFactory(), configuration.getAddresses()); 95 | } 96 | } catch (IOException e) { 97 | String message = "Impossible to instantiate a new memecached client instance, see nested exceptions"; 98 | LOG.error(message, e); 99 | throw new RuntimeException(message, e); 100 | } 101 | 102 | if (LOG.isDebugEnabled()) { 103 | LOG.debug("Running new Memcached client using " + configuration); 104 | } 105 | } 106 | 107 | /** 108 | * Converts the MyBatis object key in the proper string representation. 109 | * 110 | * @param key 111 | * the MyBatis object key. 112 | * 113 | * @return the proper string representation. 114 | */ 115 | private String toKeyString(final Object key) { 116 | // issue #1, key too long 117 | String keyString = configuration.getKeyPrefix() + StringUtils.sha1Hex(key.toString()); 118 | if (LOG.isDebugEnabled()) { 119 | LOG.debug("Object key '" + key + "' converted in '" + keyString + "'"); 120 | } 121 | return keyString; 122 | } 123 | 124 | /** 125 | * @param key 126 | * 127 | * @return 128 | */ 129 | public Object getObject(Object key) { 130 | String keyString = toKeyString(key); 131 | Object ret = retrieve(keyString); 132 | 133 | if (LOG.isDebugEnabled()) { 134 | LOG.debug("Retrived object (" + keyString + ", " + ret + ")"); 135 | } 136 | 137 | return ret; 138 | } 139 | 140 | /** 141 | * Return the stored group in Memcached identified by the specified key. 142 | * 143 | * @param groupKey 144 | * the group key. 145 | * 146 | * @return the group if was previously stored, null otherwise. 147 | */ 148 | private ObjectWithCas getGroup(String groupKey) { 149 | if (LOG.isDebugEnabled()) { 150 | LOG.debug("Retrieving group with id '" + groupKey + "'"); 151 | } 152 | 153 | ObjectWithCas groups = null; 154 | try { 155 | groups = retrieveWithCas(groupKey); 156 | } catch (Exception e) { 157 | LOG.error("Impossible to retrieve group '" + groupKey + "' see nested exceptions", e); 158 | } 159 | 160 | if (groups == null) { 161 | if (LOG.isDebugEnabled()) { 162 | LOG.debug("Group '" + groupKey + "' not previously stored"); 163 | } 164 | return null; 165 | } 166 | 167 | if (LOG.isDebugEnabled()) { 168 | LOG.debug("retrieved group '" + groupKey + "' with values " + groups); 169 | } 170 | 171 | return groups; 172 | } 173 | 174 | /** 175 | * @param keyString 176 | * 177 | * @return 178 | * 179 | * @throws Exception 180 | */ 181 | private Object retrieve(final String keyString) { 182 | Object retrieved = null; 183 | 184 | if (configuration.isUsingAsyncGet()) { 185 | Future future; 186 | if (configuration.isCompressionEnabled()) { 187 | future = client.asyncGet(keyString, new CompressorTranscoder()); 188 | } else { 189 | future = client.asyncGet(keyString); 190 | } 191 | 192 | try { 193 | retrieved = future.get(configuration.getTimeout(), configuration.getTimeUnit()); 194 | } catch (Exception e) { 195 | future.cancel(false); 196 | throw new CacheException(e); 197 | } 198 | } else { 199 | if (configuration.isCompressionEnabled()) { 200 | retrieved = client.get(keyString, new CompressorTranscoder()); 201 | } else { 202 | retrieved = client.get(keyString); 203 | } 204 | } 205 | 206 | return retrieved; 207 | } 208 | 209 | /** 210 | * Retrieves an object along with its cas using the given key 211 | * 212 | * @param keyString 213 | * 214 | * @return 215 | * 216 | * @throws Exception 217 | */ 218 | private ObjectWithCas retrieveWithCas(final String keyString) { 219 | CASValue retrieved = null; 220 | 221 | if (configuration.isUsingAsyncGet()) { 222 | Future> future; 223 | if (configuration.isCompressionEnabled()) { 224 | future = client.asyncGets(keyString, new CompressorTranscoder()); 225 | } else { 226 | future = client.asyncGets(keyString); 227 | } 228 | 229 | try { 230 | retrieved = future.get(configuration.getTimeout(), configuration.getTimeUnit()); 231 | } catch (Exception e) { 232 | future.cancel(false); 233 | throw new CacheException(e); 234 | } 235 | } else { 236 | if (configuration.isCompressionEnabled()) { 237 | retrieved = client.gets(keyString, new CompressorTranscoder()); 238 | } else { 239 | retrieved = client.gets(keyString); 240 | } 241 | } 242 | 243 | if (retrieved == null) { 244 | return null; 245 | } 246 | 247 | return new ObjectWithCas(retrieved.getValue(), retrieved.getCas()); 248 | } 249 | 250 | @SuppressWarnings("unchecked") 251 | public void putObject(Object key, Object value, String id) { 252 | String keyString = toKeyString(key); 253 | String groupKey = toKeyString(id); 254 | 255 | if (LOG.isDebugEnabled()) { 256 | LOG.debug("Putting object (" + keyString + ", " + value + ")"); 257 | } 258 | 259 | storeInMemcached(keyString, value); 260 | 261 | // add namespace key into memcached 262 | // Optimistic lock approach... 263 | boolean jobDone = false; 264 | 265 | while (!jobDone) { 266 | ObjectWithCas group = getGroup(groupKey); 267 | Set groupValues; 268 | 269 | if (group == null || group.getObject() == null) { 270 | groupValues = new HashSet(); 271 | groupValues.add(keyString); 272 | 273 | if (LOG.isDebugEnabled()) { 274 | LOG.debug("Insert/Updating object (" + groupKey + ", " + groupValues + ")"); 275 | } 276 | 277 | jobDone = tryToAdd(groupKey, groupValues); 278 | } else { 279 | groupValues = (Set) group.getObject(); 280 | groupValues.add(keyString); 281 | 282 | jobDone = storeInMemcached(groupKey, group); 283 | } 284 | } 285 | } 286 | 287 | /** 288 | * Stores an object identified by a key in Memcached. 289 | * 290 | * @param keyString 291 | * the object key 292 | * @param value 293 | * the object has to be stored. 294 | */ 295 | private void storeInMemcached(String keyString, Object value) { 296 | if (value != null && !Serializable.class.isAssignableFrom(value.getClass())) { 297 | throw new CacheException( 298 | "Object of type '" + value.getClass().getName() + "' that's non-serializable is not supported by Memcached"); 299 | } 300 | 301 | if (configuration.isCompressionEnabled()) { 302 | client.set(keyString, configuration.getExpiration(), value, new CompressorTranscoder()); 303 | } else { 304 | client.set(keyString, configuration.getExpiration(), value); 305 | } 306 | } 307 | 308 | /** 309 | * Tries to update an object value in memcached considering the cas validation. 310 | *

311 | * Returns true if the object passed the cas validation and was modified. 312 | * 313 | * @param keyString 314 | * @param value 315 | * 316 | * @return 317 | */ 318 | private boolean storeInMemcached(String keyString, ObjectWithCas value) { 319 | if (value != null && value.getObject() != null 320 | && !Serializable.class.isAssignableFrom(value.getObject().getClass())) { 321 | throw new CacheException("Object of type '" + value.getObject().getClass().getName() 322 | + "' that's non-serializable is not supported by Memcached"); 323 | } 324 | 325 | CASResponse response; 326 | 327 | if (configuration.isCompressionEnabled()) { 328 | response = client.cas(keyString, value.getCas(), value.getObject(), new CompressorTranscoder()); 329 | } else { 330 | response = client.cas(keyString, value.getCas(), value.getObject()); 331 | } 332 | 333 | return (response.equals(CASResponse.OBSERVE_MODIFIED) || response.equals(CASResponse.OK)); 334 | } 335 | 336 | /** 337 | * Tries to store an object identified by a key in Memcached. 338 | *

339 | * Will fail if the object already exists. 340 | * 341 | * @param keyString 342 | * @param value 343 | * 344 | * @return 345 | */ 346 | private boolean tryToAdd(String keyString, Object value) { 347 | if (value != null && !Serializable.class.isAssignableFrom(value.getClass())) { 348 | throw new CacheException( 349 | "Object of type '" + value.getClass().getName() + "' that's non-serializable is not supported by Memcached"); 350 | } 351 | 352 | boolean done; 353 | OperationFuture result; 354 | 355 | if (configuration.isCompressionEnabled()) { 356 | result = client.add(keyString, configuration.getExpiration(), value, new CompressorTranscoder()); 357 | } else { 358 | result = client.add(keyString, configuration.getExpiration(), value); 359 | } 360 | 361 | try { 362 | done = result.get(); 363 | } catch (InterruptedException e) { 364 | done = false; 365 | } catch (ExecutionException e) { 366 | done = false; 367 | } 368 | 369 | return done; 370 | } 371 | 372 | public Object removeObject(Object key) { 373 | String keyString = toKeyString(key); 374 | 375 | if (LOG.isDebugEnabled()) { 376 | LOG.debug("Removing object '" + keyString + "'"); 377 | } 378 | 379 | Object result = getObject(key); 380 | if (result != null) { 381 | client.delete(keyString); 382 | } 383 | return result; 384 | } 385 | 386 | @SuppressWarnings("unchecked") 387 | public void removeGroup(String id) { 388 | String groupKey = toKeyString(id); 389 | 390 | // remove namespace key into memcached 391 | // Optimistic lock approach... 392 | boolean jobDone = false; 393 | 394 | while (!jobDone) { 395 | ObjectWithCas group = getGroup(groupKey); 396 | Set groupValues; 397 | 398 | if (group == null || group.getObject() == null) { 399 | if (LOG.isDebugEnabled()) { 400 | LOG.debug("No need to flush cached entries for group '" + id + "' because is empty"); 401 | } 402 | return; 403 | } 404 | 405 | if (LOG.isDebugEnabled()) { 406 | LOG.debug("Flushing keys: " + group); 407 | } 408 | 409 | groupValues = (Set) group.getObject(); 410 | 411 | for (String key : groupValues) { 412 | client.delete(key); 413 | } 414 | 415 | if (LOG.isDebugEnabled()) { 416 | LOG.debug("Flushing group: " + groupKey); 417 | } 418 | 419 | groupValues = (Set) group.getObject(); 420 | groupValues.clear(); 421 | 422 | jobDone = storeInMemcached(groupKey, group); 423 | } 424 | } 425 | 426 | @Override 427 | protected void finalize() throws Throwable { 428 | client.shutdown(configuration.getTimeout(), configuration.getTimeUnit()); 429 | super.finalize(); 430 | } 431 | 432 | } 433 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/MemcachedConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import static java.lang.String.format; 19 | 20 | import java.net.InetSocketAddress; 21 | import java.util.List; 22 | import java.util.concurrent.TimeUnit; 23 | 24 | import net.spy.memcached.ConnectionFactory; 25 | 26 | /** 27 | * The Memcached client configuration. 28 | * 29 | * @author Simone Tripodi 30 | */ 31 | final class MemcachedConfiguration { 32 | 33 | /** 34 | * The key prefix. 35 | */ 36 | private String keyPrefix; 37 | 38 | /** 39 | * The Connection Factory used to establish the connection to Memcached server(s). 40 | */ 41 | private ConnectionFactory connectionFactory; 42 | 43 | /** 44 | * The Memcached servers. 45 | */ 46 | private List addresses; 47 | 48 | /** 49 | * The flag to switch from sync to async Memcached get. 50 | */ 51 | private boolean usingAsyncGet; 52 | 53 | /** 54 | * Compression enabled flag. 55 | */ 56 | private boolean compressionEnabled; 57 | 58 | /** 59 | * The Memcached entries expiration time. 60 | */ 61 | private int expiration; 62 | 63 | /** 64 | * The Memcached connection timeout when using async get. 65 | */ 66 | private int timeout; 67 | 68 | /** 69 | * The Memcached timeout unit when using async get. 70 | */ 71 | private TimeUnit timeUnit; 72 | 73 | /** 74 | * The flag to enable SASL Connection 75 | */ 76 | private boolean usingSASL; 77 | 78 | /** 79 | * The Memcached SASL username 80 | */ 81 | private String username; 82 | 83 | /** 84 | * The Memcached SASL password 85 | */ 86 | private String password; 87 | 88 | /** 89 | * @return the keyPrefix 90 | */ 91 | public String getKeyPrefix() { 92 | return keyPrefix; 93 | } 94 | 95 | /** 96 | * @param keyPrefix 97 | * the keyPrefix to set 98 | */ 99 | public void setKeyPrefix(String keyPrefix) { 100 | this.keyPrefix = keyPrefix; 101 | } 102 | 103 | /** 104 | * @return the connectionFactory 105 | */ 106 | public ConnectionFactory getConnectionFactory() { 107 | return connectionFactory; 108 | } 109 | 110 | /** 111 | * @param connectionFactory 112 | * the connectionFactory to set 113 | */ 114 | public void setConnectionFactory(ConnectionFactory connectionFactory) { 115 | this.connectionFactory = connectionFactory; 116 | } 117 | 118 | /** 119 | * @return the addresses 120 | */ 121 | public List getAddresses() { 122 | return addresses; 123 | } 124 | 125 | /** 126 | * @param addresses 127 | * the addresses to set 128 | */ 129 | public void setAddresses(List addresses) { 130 | this.addresses = addresses; 131 | } 132 | 133 | /** 134 | * @return the usingAsyncGet 135 | */ 136 | public boolean isUsingAsyncGet() { 137 | return usingAsyncGet; 138 | } 139 | 140 | /** 141 | * @param usingAsyncGet 142 | * the usingAsyncGet to set 143 | */ 144 | public void setUsingAsyncGet(boolean usingAsyncGet) { 145 | this.usingAsyncGet = usingAsyncGet; 146 | } 147 | 148 | /** 149 | * @return the compressionEnabled 150 | */ 151 | public boolean isCompressionEnabled() { 152 | return compressionEnabled; 153 | } 154 | 155 | /** 156 | * @param compressionEnabled 157 | * the compressionEnabled to set 158 | */ 159 | public void setCompressionEnabled(boolean compressionEnabled) { 160 | this.compressionEnabled = compressionEnabled; 161 | } 162 | 163 | /** 164 | * @return the expiration 165 | */ 166 | public int getExpiration() { 167 | return expiration; 168 | } 169 | 170 | /** 171 | * @param expiration 172 | * the expiration to set 173 | */ 174 | public void setExpiration(int expiration) { 175 | this.expiration = expiration; 176 | } 177 | 178 | /** 179 | * @return the timeout 180 | */ 181 | public int getTimeout() { 182 | return timeout; 183 | } 184 | 185 | /** 186 | * @param timeout 187 | * the timeout to set 188 | */ 189 | public void setTimeout(int timeout) { 190 | this.timeout = timeout; 191 | } 192 | 193 | /** 194 | * @return the timeUnit 195 | */ 196 | public TimeUnit getTimeUnit() { 197 | return timeUnit; 198 | } 199 | 200 | /** 201 | * @param timeUnit 202 | * the timeUnit to set 203 | */ 204 | public void setTimeUnit(TimeUnit timeUnit) { 205 | this.timeUnit = timeUnit; 206 | } 207 | 208 | /** 209 | * @return the usingSASL 210 | */ 211 | public boolean isUsingSASL() { 212 | return usingSASL; 213 | } 214 | 215 | /** 216 | * @param usingSASL 217 | * the usingSASL to set 218 | */ 219 | public void setUsingSASL(boolean usingSASL) { 220 | this.usingSASL = usingSASL; 221 | } 222 | 223 | /** 224 | * @return the username 225 | */ 226 | public String getUsername() { 227 | return username; 228 | } 229 | 230 | /** 231 | * @param username 232 | * the username to set 233 | */ 234 | public void setUsername(String username) { 235 | this.username = username; 236 | } 237 | 238 | /** 239 | * @return the password 240 | */ 241 | public String getPassword() { 242 | return password; 243 | } 244 | 245 | /** 246 | * @param password 247 | * the password to set 248 | */ 249 | public void setPassword(String password) { 250 | this.password = password; 251 | } 252 | 253 | /** 254 | * {@inheritDoc} 255 | */ 256 | @Override 257 | public int hashCode() { 258 | return hash(1, 31, addresses, compressionEnabled, connectionFactory, expiration, keyPrefix, timeUnit, timeout, 259 | usingAsyncGet, usingSASL, username, password); 260 | } 261 | 262 | /** 263 | * Computes a hashCode given the input objects. 264 | * 265 | * @param initialNonZeroOddNumber 266 | * a non-zero, odd number used as the initial value. 267 | * @param multiplierNonZeroOddNumber 268 | * a non-zero, odd number used as the multiplier. 269 | * @param objs 270 | * the objects to compute hash code. 271 | * 272 | * @return the computed hashCode. 273 | */ 274 | public static int hash(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object... objs) { 275 | int result = initialNonZeroOddNumber; 276 | for (Object obj : objs) { 277 | result = multiplierNonZeroOddNumber * result + (obj != null ? obj.hashCode() : 0); 278 | } 279 | return result; 280 | } 281 | 282 | /** 283 | * {@inheritDoc} 284 | */ 285 | @Override 286 | public boolean equals(Object obj) { 287 | if (this == obj) { 288 | return true; 289 | } 290 | if (obj == null || getClass() != obj.getClass()) { 291 | return false; 292 | } 293 | 294 | MemcachedConfiguration other = (MemcachedConfiguration) obj; 295 | return eq(addresses, other.addresses) && eq(compressionEnabled, other.compressionEnabled) 296 | && eq(connectionFactory, other.connectionFactory) && eq(expiration, other.expiration) 297 | && eq(keyPrefix, other.keyPrefix) && eq(timeUnit, other.timeUnit) && eq(timeout, other.timeout) 298 | && eq(usingAsyncGet, other.usingAsyncGet) && eq(usingSASL, other.usingSASL) && eq(username, other.username) 299 | && eq(password, other.password); 300 | } 301 | 302 | /** 303 | * Verifies input objects are equal. 304 | * 305 | * @param o1 306 | * the first argument to compare 307 | * @param o2 308 | * the second argument to compare 309 | * 310 | * @return true, if the input arguments are equal, false otherwise. 311 | */ 312 | private static boolean eq(O o1, O o2) { 313 | return o1 != null ? o1.equals(o2) : o2 == null; 314 | } 315 | 316 | /** 317 | * {@inheritDoc} 318 | */ 319 | @Override 320 | public String toString() { 321 | return format( 322 | "MemcachedConfiguration [addresses=%s, compressionEnabled=%s, connectionFactory=%s, , expiration=%s, keyPrefix=%s, timeUnit=%s, timeout=%s, usingAsyncGet=%s, usingSASL=%s, username=%s, password=%s]", 323 | addresses, compressionEnabled, connectionFactory, expiration, keyPrefix, timeUnit, timeout, usingAsyncGet, 324 | usingSASL, username, password); 325 | } 326 | 327 | } 328 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/MemcachedConfigurationBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.Properties; 23 | 24 | /** 25 | * Converter from the Config to a proper {@link MemcachedConfiguration}. 26 | * 27 | * @author Simone Tripodi 28 | */ 29 | final class MemcachedConfigurationBuilder { 30 | 31 | /** 32 | * This class instance. 33 | */ 34 | private static final MemcachedConfigurationBuilder INSTANCE = new MemcachedConfigurationBuilder(); 35 | 36 | private static final String SYSTEM_PROPERTY_MEMCACHED_PROPERTIES_FILENAME = "memcached.properties.filename"; 37 | 38 | /** 39 | * 40 | */ 41 | private static final String MEMCACHED_RESOURCE = "memcached.properties"; 42 | 43 | private final String memcachedPropertiesFilename; 44 | 45 | /** 46 | * The setters used to extract properties. 47 | */ 48 | private final List> settersRegistry = new ArrayList>(); 49 | 50 | /** 51 | * Hidden constructor, this class can't be instantiated. 52 | */ 53 | private MemcachedConfigurationBuilder() { 54 | memcachedPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_MEMCACHED_PROPERTIES_FILENAME, MEMCACHED_RESOURCE); 55 | 56 | settersRegistry.add(new StringPropertySetter("org.mybatis.caches.memcached.keyprefix", "keyPrefix", "_mybatis_")); 57 | settersRegistry.add(new StringPropertySetter("org.mybatis.caches.memcached.username", "username", "")); 58 | settersRegistry.add(new StringPropertySetter("org.mybatis.caches.memcached.password", "password", "")); 59 | 60 | settersRegistry 61 | .add(new IntegerPropertySetter("org.mybatis.caches.memcached.expiration", "expiration", 60 * 60 * 24 * 30)); 62 | settersRegistry.add(new IntegerPropertySetter("org.mybatis.caches.memcached.timeout", "timeout", 5)); 63 | settersRegistry.add(new TimeUnitSetter()); 64 | 65 | settersRegistry.add(new BooleanPropertySetter("org.mybatis.caches.memcached.asyncget", "usingAsyncGet", false)); 66 | settersRegistry 67 | .add(new BooleanPropertySetter("org.mybatis.caches.memcached.compression", "compressionEnabled", false)); 68 | settersRegistry.add(new BooleanPropertySetter("org.mybatis.caches.memcached.sasl", "usingSASL", false)); 69 | 70 | settersRegistry.add(new InetSocketAddressListPropertySetter()); 71 | settersRegistry.add(new ConnectionFactorySetter()); 72 | } 73 | 74 | /** 75 | * Return this class instance. 76 | * 77 | * @return this class instance. 78 | */ 79 | public static MemcachedConfigurationBuilder getInstance() { 80 | return INSTANCE; 81 | } 82 | 83 | /** 84 | * Parses the Config and builds a new {@link MemcachedConfiguration}. 85 | * 86 | * @return the converted {@link MemcachedConfiguration}. 87 | */ 88 | public MemcachedConfiguration parseConfiguration() { 89 | return parseConfiguration(getClass().getClassLoader()); 90 | } 91 | 92 | /** 93 | * Parses the Config and builds a new {@link MemcachedConfiguration}. 94 | * 95 | * @param the 96 | * {@link ClassLoader} used to load the {@code memcached.properties} file in classpath. 97 | * 98 | * @return the converted {@link MemcachedConfiguration}. 99 | */ 100 | public MemcachedConfiguration parseConfiguration(ClassLoader classLoader) { 101 | Properties config = new Properties(); 102 | 103 | // load the properties specified from /memcached.properties, if present 104 | InputStream input = classLoader.getResourceAsStream(memcachedPropertiesFilename); 105 | if (input != null) { 106 | try { 107 | config.load(input); 108 | } catch (IOException e) { 109 | throw new RuntimeException("An error occurred while reading classpath property '" + memcachedPropertiesFilename 110 | + "', see nested exceptions", e); 111 | } finally { 112 | try { 113 | input.close(); 114 | } catch (IOException e) { 115 | // close quietly 116 | } 117 | } 118 | } 119 | 120 | MemcachedConfiguration memcachedConfiguration = new MemcachedConfiguration(); 121 | 122 | for (AbstractPropertySetter setter : settersRegistry) { 123 | setter.set(config, memcachedConfiguration); 124 | } 125 | 126 | return memcachedConfiguration; 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/StringPropertySetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | /** 19 | * Identity String setter. 20 | * 21 | * @author Simone Tripodi 22 | */ 23 | final class StringPropertySetter extends AbstractPropertySetter { 24 | 25 | /** 26 | * Instantiates an identity String setter. 27 | * 28 | * @param propertyKey 29 | * the OSCache Config property key. 30 | * @param propertyName 31 | * the {@link MemcachedConfiguration} property name. 32 | * @param defaultValue 33 | * the property default value. 34 | */ 35 | public StringPropertySetter(final String propertyKey, final String propertyName, final String defaultValue) { 36 | super(propertyKey, propertyName, defaultValue); 37 | } 38 | 39 | /** 40 | * {@inheritDoc} 41 | */ 42 | @Override 43 | protected String convert(String property) throws Exception { 44 | return property; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/StringUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.security.MessageDigest; 19 | import java.security.NoSuchAlgorithmException; 20 | 21 | /** 22 | * Got from https://github.com/raykrueger/hibernate-memcached 23 | * 24 | * @author Ray Krueger 25 | */ 26 | public final class StringUtils { 27 | 28 | private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 29 | 'f' }; 30 | 31 | private StringUtils() { 32 | // Prevent Instantiation 33 | } 34 | 35 | public static String sha1Hex(String data) { 36 | if (data == null) { 37 | throw new IllegalArgumentException("data must not be null"); 38 | } 39 | 40 | byte[] bytes = digest("SHA1", data); 41 | 42 | return toHexString(bytes); 43 | } 44 | 45 | private static String toHexString(byte[] bytes) { 46 | int l = bytes.length; 47 | 48 | char[] out = new char[l << 1]; 49 | 50 | for (int i = 0, j = 0; i < l; i++) { 51 | out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4]; 52 | out[j++] = DIGITS[0x0F & bytes[i]]; 53 | } 54 | 55 | return new String(out); 56 | } 57 | 58 | private static byte[] digest(String algorithm, String data) { 59 | MessageDigest digest; 60 | try { 61 | digest = MessageDigest.getInstance(algorithm); 62 | } catch (NoSuchAlgorithmException e) { 63 | throw new RuntimeException(e); 64 | } 65 | 66 | return digest.digest(data.getBytes()); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/TimeUnitSetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.util.concurrent.TimeUnit; 19 | 20 | /** 21 | * Setter from String to TimeUnit representation. 22 | * 23 | * @author Simone Tripodi 24 | */ 25 | final class TimeUnitSetter extends AbstractPropertySetter { 26 | 27 | /** 28 | * Instantiates a String to TimeUnit setter. 29 | */ 30 | public TimeUnitSetter() { 31 | super("org.mybatis.caches.memcached.timeoutunit", "timeUnit", TimeUnit.SECONDS); 32 | } 33 | 34 | /** 35 | * {@inheritDoc} 36 | */ 37 | @Override 38 | protected TimeUnit convert(String property) throws Exception { 39 | return TimeUnit.valueOf(property.toUpperCase()); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/mybatis/caches/memcached/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | /** 17 | * Contains Memcached support for MyBatis Cache. 18 | * 19 | * @author Simone Tripodi 20 | */ 21 | package org.mybatis.caches.memcached; 22 | -------------------------------------------------------------------------------- /src/site/site.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 21 | 22 | 23 |

24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/site/xdoc/index.xml.vm: -------------------------------------------------------------------------------- 1 | 2 | 19 | 22 | 23 | 24 | MyBatis Memcached | Reference Documentation 25 | The MyBatis Team 26 | 27 | 28 | 29 |
30 | 31 |

Memcached is an in-memory key-value store for small chunks of arbitrary data 32 | (strings, objects) from results of database calls, API calls, or page rendering..

33 |

The Memcached integration is built on top of the spymemcached client, written by Dustin Sallings.

34 |

Users that want to use Memcached into their applications, have to download the 35 | zip bundle, decompress it and add the jars in the classpath; 36 | Apache Maven users instead can simply add in 37 | the pom.xml the following dependency:

38 | 39 | ... 40 | 41 | ${project.groupId} 42 | ${project.artifactId} 43 | ${project.version} 44 | 45 | ... 46 | ]]> 47 |

then, just configure it in the mapper XML

48 | 49 | 50 | ... 51 | ]]> 52 | 53 |

The Memcached cache is configurable by putting the 54 | /memcached.properties classpath resource; if not found, the client will 55 | use the default setting.

56 |

The following table resumes the supported configurations params; each 57 | parameter is optional, if not found in the configuration, the client will use 58 | the default value:

59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 |
PropertyDefaultDescription
org.mybatis.caches.memcached.keyprefix_mybatis_any string identifier
org.mybatis.caches.memcached.serverslocalhost:11211space separated list of ${host}:${port}
org.mybatis.caches.memcached.connectionfactorynet.spy.memcached.DefaultConnectionFactoryAny class that implements net.spy.memcached.ConnectionFactory
org.mybatis.caches.memcached.expirationthe number of seconds in 30 daysthe expiration time (in seconds)
org.mybatis.caches.memcached.asyncgetfalseflag to enable/disable the async get
org.mybatis.caches.memcached.timeout5the timeout when using async get
org.mybatis.caches.memcached.timeoutunitjava.util.concurrent.TimeUnit.SECONDSthe timeout unit when using async get
org.mybatis.caches.memcached.compressionfalseif true, objects will be GZIP compressed before putting them to Memcached
107 | 108 |

If users need to log cache operations, they can plug the Cache logging version:

109 | 110 | 111 | ... 112 | ]]> 113 |
114 | 115 | 116 |
117 | -------------------------------------------------------------------------------- /src/test/java/org/mybatis/caches/memcached/GroupTestThread.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import java.util.Random; 19 | import java.util.UUID; 20 | 21 | /** 22 | * Thread to test race conditions behavior 23 | * 24 | * @author Weisz, Gustavo E. 25 | */ 26 | public class GroupTestThread extends Thread { 27 | 28 | private long itemsToCreate; 29 | private MemcachedCache cache; 30 | 31 | public GroupTestThread(MemcachedCache cache, long itemsToCreate) { 32 | this.setCache(cache); 33 | this.setItemsToCreate(itemsToCreate); 34 | } 35 | 36 | public long getItemsToCreate() { 37 | return itemsToCreate; 38 | } 39 | 40 | public void setItemsToCreate(long itemsToCreate) { 41 | this.itemsToCreate = itemsToCreate; 42 | } 43 | 44 | public MemcachedCache getCache() { 45 | return cache; 46 | } 47 | 48 | public void setCache(MemcachedCache cache) { 49 | this.cache = cache; 50 | } 51 | 52 | @Override 53 | public void run() { 54 | Random random = new Random(); 55 | 56 | for (int i = 0; i < itemsToCreate; i++) { 57 | cache.putObject(UUID.randomUUID().toString(), "TEST"); 58 | 59 | // Wait between 1 and 10 milliseconds between each insertion 60 | try { 61 | Thread.sleep(random.nextInt(10) + 1); 62 | } catch (InterruptedException e) { 63 | } 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/org/mybatis/caches/memcached/MemcachedTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2022 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 | * https://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 | package org.mybatis.caches.memcached; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import static org.junit.jupiter.api.Assertions.assertNotNull; 20 | import static org.junit.jupiter.api.Assertions.assertNull; 21 | 22 | import java.util.ArrayList; 23 | import java.util.Arrays; 24 | import java.util.List; 25 | import java.util.Set; 26 | 27 | import org.junit.jupiter.api.BeforeEach; 28 | import org.junit.jupiter.api.Test; 29 | 30 | /** 31 | * HOW TO RUN THE TEST 32 | *

33 | * Install memcached: 34 | *

    35 | *
  • on ubuntu: open the shell and type sudo apt-get install memcached
  • 36 | *
  • on mac os x: open the terminal and type sudo port install memcached
  • 37 | *
38 | * launch mvn test. 39 | */ 40 | public final class MemcachedTestCase { 41 | 42 | private static final String DEFAULT_ID = "MEMCACHED"; 43 | 44 | private MemcachedCache cache; 45 | 46 | @BeforeEach 47 | public void newCache() { 48 | cache = new MemcachedCache(DEFAULT_ID); 49 | } 50 | 51 | @Test 52 | public void shouldDemonstrateCopiesAreEqual() { 53 | for (int i = 0; i < 100; i++) { 54 | cache.putObject(i, i); 55 | assertEquals(i, cache.getObject(i)); 56 | } 57 | } 58 | 59 | @Test 60 | public void shouldRemoveItemOnDemand() { 61 | cache.putObject(0, 0); 62 | assertNotNull(cache.getObject(0)); 63 | cache.removeObject(0); 64 | Object o = cache.getObject(0); 65 | assertNull(o); 66 | } 67 | 68 | @Test 69 | public void shouldFlushAllItemsOnDemand() { 70 | for (int i = 0; i < 5; i++) { 71 | cache.putObject(i, i); 72 | } 73 | assertNotNull(cache.getObject(0)); 74 | assertNotNull(cache.getObject(4)); 75 | cache.clear(); 76 | assertNull(cache.getObject(0)); 77 | assertNull(cache.getObject(4)); 78 | } 79 | 80 | @Test 81 | public void shouldAcceptAKeyBiggerThan250() { 82 | char[] keyChar = new char[1024]; 83 | Arrays.fill(keyChar, 'X'); 84 | String key = new String(keyChar); 85 | String value = "value"; 86 | cache.putObject(key, value); 87 | assertEquals(value, cache.getObject(key)); 88 | } 89 | 90 | /** 91 | * The group should contain all keys even if race conditions are present 92 | */ 93 | @Test 94 | public void groupShouldContainAllKeys() { 95 | 96 | long threadTestCount = 20; 97 | long valuesPerThread = 100; 98 | String mapperName = "GroupTest"; 99 | 100 | MemcachedCache newCache = new MemcachedCache(mapperName); 101 | newCache.clear(); 102 | 103 | /* 104 | * Create, run & wait 'threadTestCount' concurrent threads 105 | */ 106 | long i = 0; 107 | 108 | List threads = new ArrayList(); 109 | 110 | while (i < threadTestCount) { 111 | Thread thread = new GroupTestThread(newCache, valuesPerThread); 112 | thread.start(); 113 | threads.add(thread); 114 | i++; 115 | } 116 | 117 | for (Thread thread : threads) { 118 | try { 119 | thread.join(); 120 | } catch (InterruptedException e) { 121 | } 122 | } 123 | 124 | /* 125 | * Since each thread will create 'threadTestCount' values there should be ( 'valuesPerThread' * 'threadTestCount' ) 126 | * elements in the group, independently of any race condition. 127 | */ 128 | @SuppressWarnings("unchecked") 129 | Set keys = (Set) cache.getObject(newCache.getId()); 130 | assertNotNull(keys); 131 | 132 | long count = 0; 133 | 134 | for (@SuppressWarnings("unused") 135 | String key : keys) { 136 | count++; 137 | } 138 | 139 | assertEquals(count, valuesPerThread * threadTestCount); 140 | } 141 | 142 | } 143 | --------------------------------------------------------------------------------