Repository: lambdazen/bitsy
Branch: master
Commit: 4d76489ad8d9
Files: 194
Total size: 1.9 MB
Directory structure:
gitextract_xh4rv3j8/
├── .classpath
├── .git-blame-ignore-revs
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── .mvn/
│ └── wrapper/
│ └── maven-wrapper.properties
├── .project
├── .settings/
│ └── org.eclipse.jdt.core.prefs
├── LICENSE
├── NOTICE
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── lambdazen/
│ │ └── bitsy/
│ │ ├── BitsyEdge.java
│ │ ├── BitsyElement.java
│ │ ├── BitsyErrorCodes.java
│ │ ├── BitsyException.java
│ │ ├── BitsyFeatures.java
│ │ ├── BitsyGraph.java
│ │ ├── BitsyGraphMBean.java
│ │ ├── BitsyGraphSONModule.java
│ │ ├── BitsyIoRegistryV3d0.java
│ │ ├── BitsyIsolationLevel.java
│ │ ├── BitsyProperty.java
│ │ ├── BitsyRetryException.java
│ │ ├── BitsyState.java
│ │ ├── BitsyVertex.java
│ │ ├── BitsyVertexProperty.java
│ │ ├── ICommitChanges.java
│ │ ├── IEdge.java
│ │ ├── IGraphStore.java
│ │ ├── ITransaction.java
│ │ ├── PortDatabase.java
│ │ ├── ThreadedBitsyGraph.java
│ │ ├── UUID.java
│ │ ├── UUIDGraphBinarySerializer.java
│ │ ├── ads/
│ │ │ ├── dict/
│ │ │ │ ├── Dictionary.java
│ │ │ │ ├── Dictionary1.java
│ │ │ │ ├── Dictionary11.java
│ │ │ │ ├── Dictionary16.java
│ │ │ │ ├── Dictionary2.java
│ │ │ │ ├── Dictionary3.java
│ │ │ │ ├── Dictionary4.java
│ │ │ │ ├── Dictionary6.java
│ │ │ │ ├── Dictionary8.java
│ │ │ │ ├── DictionaryFactory.java
│ │ │ │ ├── DictionaryMax.java
│ │ │ │ └── PrimitiveDictionary.java
│ │ │ └── set/
│ │ │ ├── ArraySet.java
│ │ │ ├── ClassifierGetter.java
│ │ │ ├── CompactMultiSetMax.java
│ │ │ ├── CompactSet.java
│ │ │ ├── PrimitiveSet.java
│ │ │ ├── Set.java
│ │ │ ├── Set12.java
│ │ │ ├── Set2.java
│ │ │ ├── Set24.java
│ │ │ ├── Set3.java
│ │ │ ├── Set4.java
│ │ │ ├── Set6.java
│ │ │ ├── Set8.java
│ │ │ └── SetMax.java
│ │ ├── gremlin/
│ │ │ ├── BitsyGraphStep.java
│ │ │ └── BitsyTraversalStrategy.java
│ │ ├── index/
│ │ │ ├── BitsyIndex.java
│ │ │ ├── BitsyIndexMap.java
│ │ │ ├── EdgeIndex.java
│ │ │ ├── EdgeIndexMap.java
│ │ │ ├── IndexHelper.java
│ │ │ ├── VertexIndex.java
│ │ │ └── VertexIndexMap.java
│ │ ├── jsr223/
│ │ │ └── BitsyGremlinPlugin.java
│ │ ├── store/
│ │ │ ├── AdjacencyMap.java
│ │ │ ├── AdjacencyMapForBeans.java
│ │ │ ├── BackupJob.java
│ │ │ ├── CompactAndCopyTask.java
│ │ │ ├── EdgeBean.java
│ │ │ ├── EdgeBeanJson.java
│ │ │ ├── Endpoint.java
│ │ │ ├── FileBackedMemoryGraphStore.java
│ │ │ ├── IEdgeRemover.java
│ │ │ ├── IStringCanonicalizer.java
│ │ │ ├── ITxBatchJob.java
│ │ │ ├── IVeReorgJob.java
│ │ │ ├── IndexBean.java
│ │ │ ├── JobWithCountDownLatch.java
│ │ │ ├── LoadTask.java
│ │ │ ├── MemoryGraphStore.java
│ │ │ ├── ParallelRecordReader.java
│ │ │ ├── Record.java
│ │ │ ├── RecordReader.java
│ │ │ ├── SingleThreadedStringCanonicalizer.java
│ │ │ ├── TxBatch.java
│ │ │ ├── TxLog.java
│ │ │ ├── TxLogFlushPotential.java
│ │ │ ├── TxUnit.java
│ │ │ ├── VEObsolescencePotential.java
│ │ │ ├── VertexBean.java
│ │ │ └── VertexBeanJson.java
│ │ ├── tx/
│ │ │ ├── BitsyTransaction.java
│ │ │ └── BitsyTransactionContext.java
│ │ ├── util/
│ │ │ ├── BitsyElementIterator.java
│ │ │ ├── BufferFlusher.java
│ │ │ ├── BufferPotential.java
│ │ │ ├── BufferQueuer.java
│ │ │ ├── CommittableFileLog.java
│ │ │ ├── DefaultCommitChanges.java
│ │ │ ├── DoubleBuffer.java
│ │ │ ├── DoubleBufferThread.java
│ │ │ ├── DoubleBufferWithExecWork.java
│ │ │ ├── EdgeIterator.java
│ │ │ └── VertexIterator.java
│ │ └── wrapper/
│ │ ├── BitsyAutoReloadingEdge.java
│ │ ├── BitsyAutoReloadingGraph.java
│ │ └── BitsyAutoReloadingVertex.java
│ └── resources/
│ └── META-INF/
│ └── services/
│ └── org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin
└── test/
├── java/
│ └── com/
│ └── lambdazen/
│ └── bitsy/
│ ├── BitsyGraphIT.java
│ ├── BitsyMemGraphIT.java
│ ├── FileBasedTestCase.java
│ ├── RecoveryTest.java
│ ├── ads/
│ │ ├── dict/
│ │ │ └── DictionaryTest.java
│ │ └── set/
│ │ ├── CompactMultiSetMaxTest.java
│ │ └── SetTest.java
│ ├── store/
│ │ ├── EndpointTest.java
│ │ ├── FileBackedMemoryGraphStoreTest.java
│ │ ├── MemoryGraphStoreTest.java
│ │ ├── RecordTest.java
│ │ └── SingleThreadedStringCanonicalizerTest.java
│ ├── structure/
│ │ ├── BitsyGraphStructureTestSuite.java
│ │ ├── BitsyProcessStandardTestSuite.java
│ │ ├── BitsyTestGraphProvider.java
│ │ └── HasLabelTest.java
│ └── util/
│ ├── CommittableFileLogTest.java
│ └── DoubleBufferIT.java
└── resources/
├── com/
│ └── lambdazen/
│ └── bitsy/
│ └── util/
│ └── mobydick.txt
├── gremlin-server/
│ ├── bitsy.properties
│ └── gremlin-server-bitsy.yaml
└── recovery/
├── stage1/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
├── stage2/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
├── stage3/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
├── stage4/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
├── stage5/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
├── stage6/
│ ├── eA.txt
│ ├── eB.txt
│ ├── metaA.txt
│ ├── metaB.txt
│ ├── txA.txt
│ ├── txB.txt
│ ├── vA.txt
│ └── vB.txt
└── stage7/
├── eA.txt
├── eB.txt
├── metaA.txt
├── metaB.txt
├── txA.txt
├── txB.txt
├── vA.txt
└── vB.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
================================================
FILE: .git-blame-ignore-revs
================================================
# reformat with Maveniverse parent 39
641fdf861487e91b277fda8f06cc852842d14f60
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: "maven"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches:
- master
pull_request:
jobs:
build:
name: Verify
uses: maveniverse/parent/.github/workflows/ci.yml@release-51
with:
maven-test-run: false # ITs are currently busted and needs to go to separate module
jdk-matrix: '[ "8", "17", "21", "25" ]'
maven-matrix: '[ "3.9.12" ]'
maven-test: './mvnw clean verify -e -B -V -P run-its'
================================================
FILE: .gitignore
================================================
target
*.iml
.idea
*~
================================================
FILE: .mvn/wrapper/maven-wrapper.properties
================================================
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
================================================
FILE: .project
================================================
bitsyBitsy v3 is a small, fast, embeddable, durable in-memory graph database that is compatible with Tinkerpop3. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.org.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature
================================================
FILE: .settings/org.eclipse.jdt.core.prefs
================================================
#Thu Nov 02 18:34:43 EDT 2017
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: NOTICE
================================================
This product depends on the following components:
- Tinkerpop Gremlin (gremlin-core, gremlin-test)
http://tinkerpop.apache.org/
Apache 2.0 license
Copyright (c) 2015- The Apache Software Foundation.
- Jackson JSON processor (jackson-core, jackson-databind)
https://github.com/FasterXML/
Apache 2.0 license
Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
- Ness Computing Core Component (components-ness-core)
https://github.com/NessComputing/components-ness-core
Apache 2.0 license
Copyright (C) 2012- Ness Computing, Inc.
- SLF4J API (slf4j-api)
http://www.slf4j.org/
MIT license
Copyright (c) 2004- QOS.ch
================================================
FILE: README.md
================================================
[](https://search.maven.org/artifact/com.lambdazen.bitsy/bitsy)
Bitsy is a small, fast, embeddable, durable in-memory graph database that is compatible with Tinkerpop3.
[The project Wiki](https://github.com/lambdazen/bitsy/wiki) is the official source of documentation. The original version of the database compatible with Tinkerpop2 is available at https://bitbucket.org/lambdazen/bitsy.
### Git branching strategy
Tags are named release-[version]. Versions start with 3.0. For e.g., release-3.0
Development happens on `master` branch.
## Building it
The project **build time requirement** is [Apache Maven](https://maven.apache.org/), at least version 3.9 and Java 21.
The project **run time requirement is Java 8**.
For quick build (runs no tests nor any other plugin like javadoc)
```
mvn clean install -Dtest=void
```
For UT-only build (will run UTs too)
```
mvn clean install
```
For full build (will run UTs and ITs)
```
mvn clean install -P run-its
```
For publishing setup, see [parent POM](https://github.com/maveniverse/parent).
================================================
FILE: mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
================================================
FILE: mvnw.cmd
================================================
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
================================================
FILE: pom.xml
================================================
4.0.0eu.maveniverse.maven.parentparent51com.lambdazen.bitsybitsy3.6.5-SNAPSHOTBitsy Graph DatabaseBitsy v3 is a small, fast, embeddable, durable in-memory graph database that is compatible with Tinkerpop3https://github.com/lambdazen/bitsy/2013Apache License, Version 2.0http://www.apache.org/licenses/LICENSE-2.0.txtlambdazenSridhar Ramachandransridhar@lambdazen.comhttps://lambdazen.comcstamasTamas Cservenaktamas@cservenak.nethttps://www.cstamas.orgscm:git:https://github.com/lambdazen/bitsy.gitscm:git:https://github.com/lambdazen/bitsy.gitHEADhttps://github.com/lambdazen/bitsy/UTF-8UTF-883.7.51.7.36com.fasterxml.jackson.corejackson-core2.21.1pomimportorg.apache.tinkerpopgremlin-core${gremlin.version}com.fasterxml.jackson.corejackson-corecom.fasterxml.jackson.corejackson-databindcom.fasterxml.jackson.corejackson-annotationsorg.slf4jslf4j-api${slf4j.version}junitjunit4.13.2testorg.slf4jslf4j-simple${slf4j.version}testorg.apache.tinkerpopgremlin-test${gremlin.version}testorg.apache.maven.pluginsmaven-compiler-plugintrueorg.apache.maven.pluginsmaven-surefire-pluginfalse1false@{jacocoAgentArg} --add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMEDtruefalsetrue${java.io.tmpdir}${project.build.directory}**/*Test.java**/*TestCase.javaorg.apache.maven.pluginsmaven-failsafe-pluginfalse1false@{jacocoAgentArg} --add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMEDtruefalsetrue${java.io.tmpdir}${project.build.directory}**/*IT.java**/*ITCase.java**/*TestSuite.javaorg.apache.maven.pluginsmaven-javadoc-pluginnonefalse${maven.compiler.release}org.jacocojacoco-maven-plugin0.8.14jacocoAgentArgrun-itsorg.apache.maven.pluginsmaven-failsafe-pluginintegration-testverifycoveragecoveragetrueorg.jacocojacoco-maven-pluginprepare-agentprepare-agent-integrationreportreport-integration
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyEdge.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.ads.dict.Dictionary;
import com.lambdazen.bitsy.store.EdgeBean;
import com.lambdazen.bitsy.store.EdgeBeanJson;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
public class BitsyEdge extends BitsyElement implements Edge, IEdge {
UUID outVertexId;
UUID inVertexId;
public BitsyEdge(
UUID id,
Dictionary properties,
BitsyTransaction tx,
BitsyState state,
int version,
String label,
UUID outVertexId,
UUID inVertexId) {
super(id, label, properties, tx, state, version);
if (label == null) {
throw new IllegalArgumentException("Edge label can not be null"); // Enforced by 2.3.0 test case
}
this.outVertexId = outVertexId;
this.inVertexId = inVertexId;
}
public BitsyEdge(EdgeBean bean, BitsyTransaction tx, BitsyState state) {
this(
bean.getId(),
bean.getPropertiesDict(),
tx,
state,
bean.getVersion(),
bean.getLabel(),
bean.getOutVertexId(),
bean.getInVertexId());
}
public EdgeBeanJson asJsonBean() {
// The TX is usually not active at this point. So no checks.
return new EdgeBeanJson((UUID) id, properties, version, label, outVertexId, inVertexId, state);
}
@Override
public Iterator vertices(Direction dir) {
tx.validateForQuery(this);
if (dir != Direction.BOTH) {
Vertex ans = inOrOutVertex(dir);
return Collections.singleton(ans).iterator();
} else {
return bothVertices();
}
}
@Override
public Vertex inVertex() {
tx.validateForQuery(this);
return inOrOutVertex(Direction.IN);
}
@Override
public Vertex outVertex() {
tx.validateForQuery(this);
return inOrOutVertex(Direction.OUT);
}
@Override
public Iterator bothVertices() {
tx.validateForQuery(this);
Vertex inV = inVertex();
Vertex outV = outVertex();
return Arrays.asList(new Vertex[] {outV, inV}).iterator();
}
private Vertex inOrOutVertex(Direction dir) {
Vertex ans = tx.getVertex(getVertexId(dir));
// Vertex may disappear in READ_COMMITTED MODE
if (ans == null) {
throw new BitsyRetryException(
BitsyErrorCodes.CONCURRENT_MODIFICATION,
"The vertex in direction " + dir + " of the edge " + this.id()
+ " was removed by another transaction");
}
return ans;
}
public UUID getInVertexId() {
return inVertexId;
}
public UUID getOutVertexId() {
return outVertexId;
}
public UUID getVertexId(Direction dir) {
if (dir == Direction.IN) {
return inVertexId;
} else if (dir == Direction.OUT) {
return outVertexId;
} else {
throw new IllegalArgumentException("Unsupported direction " + dir);
}
}
public void incrementVersion() {
this.version++;
}
public void remove() {
tx.removeEdge(this);
}
public String toString() {
return StringFactory.edgeString(this);
}
@Override
// THERE ARE TWO MORE COPIES OF THIS CODE IN ELEMENT AND VERTEX
public Iterator> properties(String... propertyKeys) {
ArrayList> ans = new ArrayList>();
if (propertyKeys.length == 0) {
if (this.properties == null) return Collections.emptyIterator();
propertyKeys = this.properties.getPropertyKeys();
}
for (String key : propertyKeys) {
Property prop = property(key);
if (prop.isPresent()) ans.add(prop);
}
return ans.iterator();
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyElement.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.ads.dict.Dictionary;
import com.lambdazen.bitsy.ads.dict.Dictionary1;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
public abstract class BitsyElement implements Element {
public static enum PropType {
ELEMENT,
VERTEX,
EDGE
};
Object id;
String label;
Dictionary properties;
BitsyTransaction tx;
BitsyState state;
int version;
boolean updated;
public BitsyElement(
Object id, String label, Dictionary properties, BitsyTransaction tx, BitsyState state, int version) {
this.id = id;
this.label = label;
this.properties = properties;
this.tx = tx;
this.state = state;
this.version = version;
this.updated = false;
}
@Override
public Object id() {
// No TX check to return the ID
return id;
}
@Override
public String label() {
// There is no Tx validation for label because it is used even after deletion to update indexes, etc.
return label;
}
@Override
public Graph graph() {
return tx.graph();
}
public Dictionary getPropertyDict() {
return properties;
}
@Override
public T value(String key) {
tx.validateForQuery(this);
if (properties == null) {
return null;
} else {
return (T) (properties.getProperty(key));
}
}
@Override
public Set keys() {
tx.validateForQuery(this);
if (properties == null) {
return Collections.emptySet();
} else {
return new CopyOnWriteArraySet(Arrays.asList(properties.getPropertyKeys()));
}
}
public T removeProperty(String key) {
markForUpdate();
if (properties == null) {
return null;
} else {
Object ans = properties.getProperty(key);
properties = properties.removeProperty(key);
return (T) ans;
}
}
@Override
public Property property(String key, T value) {
if (value == null) {
throw new IllegalArgumentException(
"A null property can not be stored. You can call removeProperty() instead");
}
markForUpdate();
if (key == null) {
throw new IllegalArgumentException("Expecting non-null key in setProperty");
} else if (key.length() == 0) {
throw new IllegalArgumentException("Expecting non-empty key in setProperty");
} else if (key.equals("id")) {
throw new IllegalArgumentException("Can not set the 'id' property on an element");
} else if (key.equals("label")) {
throw new IllegalArgumentException("Can not set the 'label' property on an element");
} else if (key.charAt(0) == '~') {
throw new IllegalArgumentException("Can not set a property beginning with ~ on an element");
}
if (this.properties == null) {
this.properties = new Dictionary1(key, value);
} else {
this.properties = properties.setProperty(key, value);
}
assert (properties != null);
return new BitsyProperty(this, key, value);
}
// WARNING: THERE IS ONE MORE COPY OF THIS CODE IN VERTEX
@Override
public Property property(String key) {
T value = value(key);
if (value == null) {
return Property.empty();
} else {
return new BitsyProperty(this, key, value);
}
}
// WARNING: THERE ARE TWO MORE COPIES OF THIS CODE IN VERTEX AND EDGE
@Override
public Iterator extends Property> properties(String... propertyKeys) {
ArrayList> ans = new ArrayList>();
if (propertyKeys.length == 0) {
if (this.properties == null) return Collections.emptyIterator();
propertyKeys = this.properties.getPropertyKeys();
}
for (String key : propertyKeys) {
Property prop = property(key);
if (prop.isPresent()) ans.add(prop);
}
return ans.iterator();
}
/** This method prepares the vertex/edge for an update */
public void markForUpdate() {
if (!updated) {
updated = true;
// Make a copy of the underlying property map, if non-null
if (properties != null) {
properties = properties.copyOf();
}
tx.markForPropertyUpdate(this);
}
}
@Override
public abstract void remove();
public BitsyState getState() {
return state;
}
public void setState(BitsyState state) {
this.state = state;
}
public int getVersion() {
return version;
}
public ITransaction getTransaction() {
return tx;
}
// Moved to hashCode and equals from ElementHelper -- to pass Gremlin tests
@Override
public int hashCode() {
return ElementHelper.hashCode(this);
}
@Override
public boolean equals(Object object) {
return ElementHelper.areEqual(this, object);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyErrorCodes.java
================================================
package com.lambdazen.bitsy;
public enum BitsyErrorCodes {
INTERNAL_ERROR {
public String toString() {
return "INTERNAL_ERROR: An internal error occurred";
}
},
ACCESS_OUTSIDE_TX_SCOPE {
public String toString() {
return "ACCESS_OUTSIDE_TX_SCOPE: A vertex/edge was accessed outside the scope of the transaction that created it";
}
},
ELEMENT_ALREADY_DELETED {
public String toString() {
return "ELEMENT_ALREADY_DELETED: The vertex/edge being accessed has already been deleted";
}
},
ADDING_EDGE_TO_A_DELETED_VERTEX {
public String toString() {
return "ADDING_EDGE_TO_A_DELETED_VERTEX: A edge was added in a transaction to (Direction.IN) a vertex that was deleted in the same transaction";
}
},
ADDING_EDGE_FROM_A_DELETED_VERTEX {
public String toString() {
return "ADDING_EDGE_FROM_A_DELETED_VERTEX: A edge was added in a transaction from (Direction.OUT) a vertex that was deleted in the same transaction";
}
},
EXCEPTION_IN_FLUSH {
public String toString() {
return "EXCEPTION_IN_FLUSH: The given exception occurred in the different thread while flushing a double buffer";
}
},
BAD_DB_PATH {
public String toString() {
return "BAD_DB_PATH: The given path to the database is not a directory";
}
},
ERROR_INITIALIZING_DB_FILES {
public String toString() {
return "ERROR_INITIALIZING_DB_FILES: The given database file could not be opened or initialized";
}
},
ERROR_READING_FROM_FILE {
public String toString() {
return "ERROR_READING_FROM_FILE: A fatal error occurred while reading from a file. The database may need to be restarted after investigating the root cause";
}
},
ERROR_WRITING_TO_FILE {
public String toString() {
return "ERROR_WRITING_TO_TX_FILE: A fatal error occurred while writing to a transaction file. The database may need to be restarted after investigating the root cause";
}
},
TRANSACTION_INTERRUPTED {
public String toString() {
return "TRANSACTION_INTERRUPTED: The given InterruptedException occurred during a transaction";
}
},
SERIALIZATION_ERROR {
public String toString() {
return "SERIALIZATION_ERROR: The given exception occurred while serializing a commit block using Jackson JSON API";
}
},
ADDING_EDGE_WITH_VERTEX_FROM_ANOTHER_TX {
public String toString() {
return "ADDING_EDGE_WITH_VERTICES_FROM_ANOTHER_TX: An edge was added in a transaction with an endpoint vertex belonging to another transaction";
}
},
REMOVING_VERTEX_FROM_ANOTHER_TX {
public String toString() {
return "REMOVING_VERTEX_FROM_ANOTHER_TX: A vertex was removed in a transaction different from the one in which it was loaded";
}
},
REMOVING_EDGE_FROM_ANOTHER_TX {
public String toString() {
return "REMOVING_EDGE_FROM_ANOTHER_TX: An edge was removed in a transaction different from the one in which it was loaded";
}
},
CHECKSUM_MISMATCH {
public String toString() {
return "CHECKSUM_MISMATCH: Encountered a checksum mismatch while loading a database file";
}
},
CONCURRENT_MODIFICATION {
public String toString() {
return "CONCURRENT_MODIFICATION: A vertex or edge loaded in a transaction was concurrently modified by another transaction. Please retry this transaction";
}
},
ERROR_IN_FILE_HEADER {
public String toString() {
return "ERROR_IN_FILE_HEADER: A fatal error occured while parsing the first line (header) in a database file";
}
},
INCOMPLETE_TX_FLUSH {
public String toString() {
return "INCOMPLETE_TX_FLUSH: A V/E file was not fully flushed when the database was previously shutdown";
}
},
DATABASE_IS_CORRUPT {
public String toString() {
return "DATABASE_IS_CORRUPT: The given error is fatal and the database can not be loaded";
}
},
JAVA_DESERIALIZATION_ERROR {
public String toString() {
return "DESERIALIZATION_ERROR: An error occurred while de-serializing a Java Serializable object";
}
},
INDEX_ALREADY_EXISTS {
public String toString() {
return "INDEX_ALREADY_EXISTS: The given index already exists in the database";
}
},
UNSUPPORTED_INDEX_TYPE {
public String toString() {
return "UNSUPPORTED_INDEX_TYPE: Indexes are only supported on Vertex and Edge classes";
}
},
MISSING_INDEX {
public String toString() {
return "MISSING_INDEX: A vertex/edge query on a matching key-value pair was performed without creating an index for that key";
}
},
OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS {
public String toString() {
return "OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS: The requested operation can not be performed on memory-only graphs";
}
},
FULL_GRAPH_SCANS_ARE_DISABLED {
public String toString() {
return "FULL_GRAPH_SCANS_ARE_DISABLED: The requested operation can not be performed because the BitsyGraph was constructed with the allowFullGraphScans option disabled";
}
},
BAD_BACKUP_PATH {
public String toString() {
return "BAD_BACKUP_PATH: The given path to backup the database is not an empty directory";
}
},
BACKUP_IN_PROGRESS {
public String toString() {
return "BACKUP_IN_PROGRESS: A scheduled backup task is already in progress. Please try after a some time";
}
},
BACKUP_INTERRUPTED {
public String toString() {
return "BACKUP_INTERRUPTED: The given InterruptedException occurred while waiting for a backup to be performed";
}
},
BACKUP_FAILED {
public String toString() {
return "BACKUP_FAILED: The given exception occurred during a backup operation";
}
},
FLUSH_INTERRUPTED {
public String toString() {
return "FLUSH_INTERRUPTED: The given InterruptedException occurrend while waiting for a flush operation on a transaction log to complete";
}
},
INSTANCE_ALREADY_EXISTS {
public String toString() {
return "INSTANCE_ALREADY_EXISTS: A BitsyGraph object with the same path has been registered with the MBeanServer. Creating multiple instances of BitsyGraph (without calling shutdown) will cause data corruption";
}
},
ERROR_REGISTERING_TO_MBEAN_SERVER {
public String toString() {
return "ERROR_REGISTERING_TO_MBEAN_SERVER: A BitsyGraph object could not be registered with the MBeanServer";
}
},
MAJOR_VERSION_MISMATCH {
public String toString() {
return "MAJOR_VERSION_MISMATCH: The database loaded was created with by different major version of Bitsy. Please run 'java com.lambdazen.bitsy.PortDatabase' to upgrade or downgrade the database";
}
},
NO_OLAP_SUPPORT {
public String toString() {
return "NO_OLAP_SUPPORT: Bitsy is not designed to be an OLAP graph";
}
},
NO_MULTI_PROPERTY_SUPPORT {
public String toString() {
return "NO_MULTI_PROPERTY_SUPPORT: Bitsy does not support multi-properties. Please use a list value instead";
}
},
NO_META_PROPERTY_SUPPORT {
public String toString() {
return "NO_META_PROPERTY_SUPPORT: Bitsy does not support meta-properties. Please use property keys such as a.b.c instead";
}
},
NO_CUSTOM_ID_SUPPORT {
public String toString() {
return "NO_CUSTOM_ID_SUPPORT: Bitsy does not support user-supplied IDs for vertices and edges, only auto-generated UUIDs. Please move this to an indexed key";
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyException.java
================================================
package com.lambdazen.bitsy;
public class BitsyException extends RuntimeException {
private static final long serialVersionUID = -5310572247323732287L;
BitsyErrorCodes code;
public BitsyException(BitsyErrorCodes code) {
super(code.toString());
this.code = code;
}
public BitsyException(BitsyErrorCodes code, String s) {
super(code.toString() + ". " + s);
this.code = code;
}
public BitsyException(BitsyErrorCodes code, String s, Throwable t) {
super(code.toString() + ". " + s, t);
this.code = code;
}
public BitsyErrorCodes getErrorCode() {
return code;
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyFeatures.java
================================================
package com.lambdazen.bitsy;
import org.apache.tinkerpop.gremlin.structure.Graph.Features;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
public class BitsyFeatures implements Features {
private final GraphFeatures graphFeatures = new BitsyGraphFeatures();
private final VertexFeatures vertexFeatures = new BitsyVertexFeatures();
private final EdgeFeatures edgeFeatures = new BitsyEdgeFeatures();
private boolean isPersistent;
public BitsyFeatures(boolean isPersistent) {
this.isPersistent = isPersistent;
}
@Override
public GraphFeatures graph() {
return graphFeatures;
}
@Override
public EdgeFeatures edge() {
return edgeFeatures;
}
@Override
public VertexFeatures vertex() {
return vertexFeatures;
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
public class BitsyGraphFeatures implements Features.GraphFeatures {
private final Features.VariableFeatures variablesFeatures = new BitsyVariableFeatures();
@Override
public boolean supportsComputer() {
return false;
}
@Override
public Features.VariableFeatures variables() {
return variablesFeatures;
}
@Override
public boolean supportsPersistence() {
return isPersistent;
}
// Yes for transactions
// TODO: Change from no for threaded transactions to yes -- semantics seems to have changed per
// shouldNotReuseThreadedTransaction
@Override
public boolean supportsThreadedTransactions() {
return false;
}
}
public class BitsyVariableFeatures implements Features.VariableFeatures {
@Override
public boolean supportsVariables() {
return false;
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
}
public class BitsyVertexFeatures implements Features.VertexFeatures {
private final Features.VertexPropertyFeatures vertexPropertyFeatures = new BitsyGraphPropertyFeatures();
@Override
public Features.VertexPropertyFeatures properties() {
return vertexPropertyFeatures;
}
@Override
public boolean supportsMetaProperties() {
return false;
}
@Override
public boolean supportsMultiProperties() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
// Yes for add and remove vertices
}
public class BitsyEdgeFeatures implements Features.EdgeFeatures {
private final Features.EdgePropertyFeatures edgePropertyFeatures = new BitsyGraphPropertyFeatures();
@Override
public Features.EdgePropertyFeatures properties() {
return edgePropertyFeatures;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
// Yes for add and remove edges
}
public class BitsyGraphPropertyFeatures implements Features.VertexPropertyFeatures, Features.EdgePropertyFeatures {
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return true;
}
@Override
public boolean supportsUuidIds() {
return false;
}
// Yes for all property types
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyGraph.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.gremlin.BitsyTraversalStrategy;
import com.lambdazen.bitsy.store.FileBackedMemoryGraphStore;
import com.lambdazen.bitsy.store.MemoryGraphStore;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import com.lambdazen.bitsy.tx.BitsyTransactionContext;
import com.lambdazen.bitsy.wrapper.BitsyAutoReloadingGraph;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.Io;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Graph.OptIn("com.lambdazen.bitsy.structure.BitsyGraphStructureTestSuite")
@Graph.OptIn("com.lambdazen.bitsy.structure.BitsyProcessStandardTestSuite")
/** Bitsy 3.0 compatible with Tinkerpop 3.0 */
public class BitsyGraph implements Graph, BitsyGraphMBean {
private static final Logger log = LoggerFactory.getLogger(BitsyGraph.class);
public static boolean IS_ANDROID = "The Android Project".equals(System.getProperty("java.specification.vendor"));
// Configuration keys
public static final String DB_PATH_KEY = "dbPath";
public static final String ALLOW_FULL_GRAPH_SCANS_KEY = "allowFullGraphScans";
public static final String DEFAULT_ISOLATION_LEVEL_KEY = "defaultIsolationLevel";
public static final String TX_LOG_THRESHOLD_KEY = "txLogThreshold";
public static final String REORG_FACTOR_KEY = "reorgFactor";
public static final String CREATE_DIR_IF_MISSING_KEY = "createDirIfMissing";
public static final String VERTEX_INDICES_KEY = "vertexIndices";
public static final String EDGE_INDICES_KEY = "edgeIndices";
public static final double DEFAULT_REORG_FACTOR = 1;
public static final long DEFAULT_TX_LOG_THRESHOLD = 4 * 1024 * 1024;
private boolean allowFullGraphScans;
private boolean isPersistent;
private Path dbPath;
private ThreadLocal curTransaction;
private ThreadLocal curTransactionContext;
private IGraphStore graphStore;
private Features bitsyFeatures;
private ObjectName objectName;
private BitsyIsolationLevel defaultIsolationLevel;
private boolean createDirIfMissing = false;
private Configuration origConfig;
static {
try {
TraversalStrategies.GlobalCache.registerStrategies(
BitsyGraph.class,
TraversalStrategies.GlobalCache.getStrategies(Graph.class)
.clone()
.addStrategies(BitsyTraversalStrategy.instance()));
TraversalStrategies.GlobalCache.registerStrategies(
BitsyAutoReloadingGraph.class,
TraversalStrategies.GlobalCache.getStrategies(Graph.class)
.clone()
.addStrategies(BitsyTraversalStrategy.instance()));
} catch (java.lang.BootstrapMethodError e) {
// Known issue with Android
System.err.println("Not registering traversal strategies");
e.printStackTrace();
}
}
// Protected constructor used by ThreadedBitsyGraph
protected BitsyGraph(char isThreaded, boolean allowFullGraphScans) {
// char isThreaded is used to distinguish this constructor from others
this.allowFullGraphScans = allowFullGraphScans;
}
public BitsyGraph() {
this(true);
}
public BitsyGraph(boolean allowFullGraphScans) {
this(null, true, -1, -1);
}
public BitsyGraph(Path dbPath) {
this(dbPath, true, DEFAULT_TX_LOG_THRESHOLD, DEFAULT_REORG_FACTOR); // Default tx log size is 4MB
}
/**
* Constructor with all configurable parameters
* @param dbPath path to the database files
* @param allowFullGraphScans whether/not iterations on vertices and edges should be supported
* @param txLogThreshold the size of the transaction in bytes after which it will be scheduled to move to V/E files
* @param reorgFactor V/E reorgs are triggered when the size of the V/E files exceeds the initial size by (1 + factor)
*/
public BitsyGraph(Path dbPath, boolean allowFullGraphScans, long txLogThreshold, double reorgFactor) {
this(dbPath, allowFullGraphScans, txLogThreshold, reorgFactor, false);
}
/**
* Constructor with all configurable parameters
* @param dbPath path to the database files
* @param allowFullGraphScans whether/not iterations on vertices and edges should be supported
* @param txLogThreshold the size of the transaction in bytes after which it will be scheduled to move to V/E files
* @param reorgFactor V/E reorgs are triggered when the size of the V/E files exceeds the initial size by (1 + factor)
* @param createDirIfMissing create the Bitsy directory if it is missing
*/
public BitsyGraph(
Path dbPath,
boolean allowFullGraphScans,
long txLogThreshold,
double reorgFactor,
boolean createDirIfMissing) {
this.dbPath = dbPath;
this.allowFullGraphScans = allowFullGraphScans;
this.curTransactionContext = new ThreadLocal();
this.curTransaction = new ThreadLocal();
this.defaultIsolationLevel = BitsyIsolationLevel.READ_COMMITTED;
this.createDirIfMissing = createDirIfMissing;
if (IS_ANDROID) {
if (isPersistent()) {
// Load from files
this.graphStore = new FileBackedMemoryGraphStore(
new MemoryGraphStore(allowFullGraphScans),
dbPath,
txLogThreshold,
reorgFactor,
createDirIfMissing);
} else {
this.graphStore = new MemoryGraphStore(allowFullGraphScans);
}
} else {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
if (isPersistent()) {
// Make sure that another BitsyGraph doesn't exist with the same path
try {
this.objectName =
new ObjectName("com.lambdazen.bitsy", "path", ObjectName.quote(dbPath.toString()));
} catch (MalformedObjectNameException e) {
throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Bug in quoting ObjectName", e);
}
// Check registry
if (server.isRegistered(objectName)) {
throw new BitsyException(BitsyErrorCodes.INSTANCE_ALREADY_EXISTS, "Path " + dbPath.toString());
}
// Load from files
this.graphStore = new FileBackedMemoryGraphStore(
new MemoryGraphStore(allowFullGraphScans),
dbPath,
txLogThreshold,
reorgFactor,
createDirIfMissing);
} else {
this.graphStore = new MemoryGraphStore(allowFullGraphScans);
}
// Register this to the MBeanServer
if (objectName != null) {
try {
server.registerMBean(this, objectName);
} catch (Exception e) {
throw new BitsyException(
BitsyErrorCodes.ERROR_REGISTERING_TO_MBEAN_SERVER, "Encountered exception", e);
}
}
}
this.bitsyFeatures = new BitsyFeatures(isPersistent);
}
/**
* Constructor with a Configuration object with String dbPath, boolean allowFullGraphScans, long txLogThreshold and double reorgFactor
*/
public BitsyGraph(Configuration configuration) {
this(
Paths.get(configuration.getString(DB_PATH_KEY)),
configuration.getBoolean(ALLOW_FULL_GRAPH_SCANS_KEY, Boolean.TRUE),
configuration.getLong(TX_LOG_THRESHOLD_KEY, DEFAULT_TX_LOG_THRESHOLD),
configuration.getDouble(REORG_FACTOR_KEY, DEFAULT_REORG_FACTOR),
configuration.getBoolean(CREATE_DIR_IF_MISSING_KEY, false));
String isoLevelStr = configuration.getString(DEFAULT_ISOLATION_LEVEL_KEY);
if (isoLevelStr != null) {
setDefaultIsolationLevel(BitsyIsolationLevel.valueOf(isoLevelStr));
}
String vertexIndices = configuration.getString(VERTEX_INDICES_KEY);
if (vertexIndices != null) {
createIndices(Vertex.class, vertexIndices);
}
String edgeIndices = configuration.getString(EDGE_INDICES_KEY);
if (edgeIndices != null) {
createIndices(Edge.class, edgeIndices);
}
this.origConfig = configuration;
}
private void createIndices(Class elemType, String vertexIndices) {
for (String indexKey : vertexIndices.split(",")) {
try {
createKeyIndex(indexKey.trim(), elemType);
} catch (BitsyException ex) {
if (ex.getErrorCode() == BitsyErrorCodes.INDEX_ALREADY_EXISTS) {
// That's fine
} else {
throw ex;
}
}
}
}
public static final BitsyGraph open(Configuration configuration) {
return new BitsyGraph(configuration);
}
public String toString() {
if (dbPath != null) {
return "bitsygraph[" + dbPath + "]";
} else {
return "bitsygraph[]";
}
}
/** This method can be used to check if the current thread has an ongoing transaction */
public boolean isTransactionActive() {
ITransaction tx = curTransaction.get();
return (tx != null);
}
public boolean isPersistent() {
return (dbPath != null);
}
public boolean isFullGraphScanAllowed() {
return allowFullGraphScans;
}
public BitsyIsolationLevel getDefaultIsolationLevel() {
return defaultIsolationLevel;
}
public void setDefaultIsolationLevel(BitsyIsolationLevel level) {
this.defaultIsolationLevel = level;
}
public BitsyIsolationLevel getTxIsolationLevel() {
return getTx().getIsolationLevel();
}
public void setTxIsolationLevel(BitsyIsolationLevel level) {
getTx().setIsolationLevel(level);
}
public double getReorgFactor() {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Reorg factor is only defined for persistent graphs (with a defined path to DB)");
} else {
return ((FileBackedMemoryGraphStore) graphStore)
.getVEReorgPotential()
.getFactor();
}
}
public void setReorgFactor(double factor) {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Reorg factor is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStore) graphStore).getVEReorgPotential().setFactor(factor);
}
}
public int getMinLinesPerReorg() {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Reorg factor is only defined for persistent graphs (with a defined path to DB)");
} else {
return ((FileBackedMemoryGraphStore) graphStore)
.getVEReorgPotential()
.getMinLinesPerReorg();
}
}
public void setMinLinesPerReorg(int minLinesPerReorg) {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Reorg factor is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStore) graphStore).getVEReorgPotential().setMinLinesPerReorg(minLinesPerReorg);
}
}
public long getTxLogThreshold() {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Transaction log threshold is only defined for persistent graphs (with a defined path to DB)");
} else {
return ((FileBackedMemoryGraphStore) graphStore)
.getTxLogFlushPotential()
.getTxLogThreshold();
}
}
public void setTxLogThreshold(long txLogThreshold) {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Transaction log threshold is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStore) graphStore).getTxLogFlushPotential().setTxLogThreshold(txLogThreshold);
}
}
/** This method flushes the transaction log to the V/E text files */
public void flushTxLog() {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Transaction log threshold is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStore) graphStore).flushTxLog();
}
}
/** This method backs up the database while it is still operational. Only one backup can be in progress at a time.
*
* @param pathToDir directory to which the database must be backed up.
*/
public void backup(String pathToDir) {
backup(Paths.get(pathToDir));
}
/** This method backs up the database while it is still operational. Only one backup can be in progress at a time.
*
* @param pathToDir directory to which the database must be backed up.
*/
public void backup(Path pathToDir) {
if (!isPersistent()) {
throw new BitsyException(
BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS,
"Transaction log threshold is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStore) graphStore).backup(pathToDir);
}
}
protected BitsyTransaction getTx() {
BitsyTransaction tx = curTransaction.get();
if ((tx == null) || !tx.isOpen()) {
BitsyTransactionContext txContext = curTransactionContext.get();
if (txContext == null) {
txContext = new BitsyTransactionContext(graphStore);
curTransactionContext.set(txContext);
}
tx = new BitsyTransaction(txContext, defaultIsolationLevel, this);
curTransaction.set(tx);
}
return tx;
}
@Override
public ITransaction tx() {
return getTx();
}
/* UNIMPLEMENTED OLAP METHODS */
@Override
public GraphComputer compute() {
throw new UnsupportedOperationException(
"Bitsy doesn't support the compute() method", new BitsyException(BitsyErrorCodes.NO_OLAP_SUPPORT));
}
@Override
public GraphComputer compute(Class graphComputerClass) {
throw new UnsupportedOperationException(
"Bitsy doesn't support the compute() method", new BitsyException(BitsyErrorCodes.NO_OLAP_SUPPORT));
}
@Override
public I io(final Io.Builder builder) {
return (I) builder.graph(this)
.onMapper(m -> m.addRegistry(BitsyIoRegistryV3d0.instance()))
.create();
}
/* FEATURES */
@Override
public Graph.Features features() {
return bitsyFeatures;
}
/* CONFIGURATION */
@Override
public Configuration configuration() {
if (this.origConfig != null) {
return this.origConfig;
} else {
Configuration ans = new BaseConfiguration();
ans.setProperty(DB_PATH_KEY, dbPath.toString());
ans.setProperty(ALLOW_FULL_GRAPH_SCANS_KEY, allowFullGraphScans);
ans.setProperty(DEFAULT_ISOLATION_LEVEL_KEY, defaultIsolationLevel.toString());
ans.setProperty(TX_LOG_THRESHOLD_KEY, getTxLogThreshold());
ans.setProperty(REORG_FACTOR_KEY, getReorgFactor());
ans.setProperty(CREATE_DIR_IF_MISSING_KEY, createDirIfMissing);
ans.setProperty(VERTEX_INDICES_KEY, String.join(",", getIndexedKeys(Vertex.class)));
ans.setProperty(EDGE_INDICES_KEY, String.join(",", getIndexedKeys(Vertex.class)));
return ans;
}
}
private void validateHomogenousIds(final Object[] ids) {
final Class firstClass = ids[0].getClass();
for (int i = 1; i < ids.length; i++) {
Class curClass = ids[i].getClass();
if (!curClass.equals(firstClass)) {
throw new IllegalArgumentException(
"Argument " + i + " has class " + curClass + " which mismatches arg 0's class " + firstClass);
}
}
}
@Override
public Vertex addVertex(Object... keyValues) {
if (keyValues == null) {
throw new IllegalArgumentException("Expecting non-null arguments in addVertex");
} else if (keyValues.length % 2 == 1) {
throw new IllegalArgumentException(
"Expecting even number of items in the keyValue array. Found " + keyValues.length);
}
// Validate first
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] == T.id) {
// We don't support custom IDs
throw new UnsupportedOperationException(
"Encountered T.id in addVertex", new BitsyException(BitsyErrorCodes.NO_CUSTOM_ID_SUPPORT));
} else if (keyValues[i] == null) {
throw new IllegalArgumentException("Encountered a null key in argument #" + i);
} else if (keyValues[i + 1] == null) {
throw new IllegalArgumentException("Encountered a null value in argument #" + i);
} else if (keyValues[i] == T.label) {
// That's fine
} else if (!(keyValues[i] instanceof String)) {
throw new IllegalArgumentException(
"Encountered a non-string key: " + keyValues[i] + " in argument #" + i);
}
}
// Do the work
final String label = ElementHelper.getLabelValue(keyValues).orElse(null);
BitsyTransaction tx = getTx();
BitsyVertex vertex = new BitsyVertex(UUID.randomUUID(), label, null, tx, BitsyState.M, 0);
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] == T.label) {
// Already found it
} else {
String key = (String) keyValues[i];
vertex.property(key, keyValues[i + 1]);
}
}
tx.addVertex(vertex);
return vertex;
}
@Override
public Iterator vertices(Object... vertexIds) {
if (vertexIds.length == 0) {
if (!allowFullGraphScans) {
throw new BitsyException(BitsyErrorCodes.FULL_GRAPH_SCANS_ARE_DISABLED, "Can not evaluate vertices()");
}
final ITransaction tx = getTx();
return tx.getAllVertices();
} else if (vertexIds.length == 1) {
Vertex vertex = getVertex(vertexIds[0]);
if (vertex == null) {
return Collections.emptyList().iterator();
} else {
return Collections.singletonList(vertex).iterator();
}
} else {
validateHomogenousIds(vertexIds);
List ans = new ArrayList();
for (Object vertexId : vertexIds) {
Vertex vertex = getVertex(vertexId);
if (vertex != null) {
ans.add(vertex);
}
}
return ans.iterator();
}
}
private Vertex getVertex(Object id) {
if (id == null) {
throw new IllegalArgumentException("The vertex ID passed to getVertex() is null");
}
Vertex ans;
if (id instanceof UUID) {
ans = getTx().getVertex((UUID) id);
} else if (id instanceof String) {
// Get the UUID from the string representation -- may fail
UUID uuid;
try {
uuid = UUID.fromString((String) id);
} catch (IllegalArgumentException e) {
// Decoding failed
return null;
}
ans = getTx().getVertex(uuid);
} else if (id instanceof Vertex) {
return getTx().getVertex((UUID) ((Vertex) id).id());
} else {
// Wrong type
ans = null;
}
return ans;
}
private Edge getEdge(Object id) {
if (id == null) {
throw new IllegalArgumentException("The edge ID passed to getEdge() is null");
}
if (id instanceof UUID) {
return getTx().getEdge((UUID) id);
} else if (id instanceof String) {
// Get the UUID from the string representation -- may fail
UUID uuid;
try {
uuid = UUID.fromString((String) id);
} catch (IllegalArgumentException e) {
// Decoding failed
return null;
}
return getTx().getEdge(uuid);
} else if (id instanceof Edge) {
return getTx().getEdge((UUID) ((Edge) id).id());
} else {
// Wrong type
return null;
}
}
public Iterator edges(Object... edgeIds) {
if (edgeIds.length == 0) {
if (!allowFullGraphScans) {
throw new BitsyException(BitsyErrorCodes.FULL_GRAPH_SCANS_ARE_DISABLED, "Can not evaluate edges()");
}
final ITransaction tx = getTx();
return tx.getAllEdges();
} else if (edgeIds.length == 1) {
Edge edge = getEdge(edgeIds[0]);
if (edge == null) {
return Collections.emptyList().iterator();
} else {
return Collections.singletonList(edge).iterator();
}
} else {
validateHomogenousIds(edgeIds);
List ans = new ArrayList();
for (Object edgeId : edgeIds) {
Edge edge = getEdge(edgeId);
if (edge != null) {
ans.add(edge);
}
}
return ans.iterator();
}
}
public void shutdown() {
try {
// As per Blueprints tests, shutdown() implies automatic commit
BitsyTransaction tx = curTransaction.get();
if ((tx != null) && tx.isOpen()) {
tx.commit();
tx = null;
}
// Shutdown the underlying store
graphStore.shutdown();
// remove threadlocal to avoid OOM
if (curTransaction != null) {
try {
curTransaction.remove();
curTransactionContext.remove();
} catch (Throwable t) {
// Ignore
}
}
} finally {
if (this.objectName != null) {
// Deregister from JMX
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
server.unregisterMBean(objectName);
} catch (Exception e) {
log.error("Error unregistering MBean named " + objectName + " from the MBeanServer", e);
}
objectName = null;
}
}
}
// Key indexes from TP2 -- now requires TraversalStrategy
public void createKeyIndex(String key, Class elementType) {
graphStore.createKeyIndex(key, elementType);
}
public void dropKeyIndex(String key, Class elementType) {
graphStore.dropKeyIndex(key, elementType);
}
public Set getIndexedKeys(Class elementType) {
return graphStore.getIndexedKeys(elementType);
}
public Iterator verticesByIndex(final String key, final Object value) {
final ITransaction tx = getTx();
return tx.lookupVertices(key, value);
}
public Iterator edgesByIndex(final String key, final Object value) {
final ITransaction tx = getTx();
return tx.lookupEdges(key, value);
}
public IGraphStore getStore() {
return graphStore;
}
@Override
public void close() throws Exception {
this.shutdown();
}
@Override
public Variables variables() {
throw new UnsupportedOperationException("Bitsy doesn't support variables. Please store the data in a vertex");
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyGraphMBean.java
================================================
package com.lambdazen.bitsy;
public interface BitsyGraphMBean {
/**
* Returns the reorgFactor which typically determines when the V?.txt and
* E?.txt file will be reorganized. Reorganization is triggered only when the
* total number of new vertices and edges added is more than the factor
* multiplied by the original number of vertices and edges. Default value is 1.
*/
public double getReorgFactor();
/**
* Set the reorgFactor. A higher number indicates fewer file operations, but
* more disk space and startup time in the worst case. Default value is 1.
*/
public void setReorgFactor(double factor);
/**
* Returns the minimum number of vertices and edges that must be added
* before a reorganization is considered. This rule is used in combination
* with the reorgFactor. Default value is 1000.
*/
public int getMinLinesPerReorg();
/**
* Modify the minimum lines to be added before a reorganization is
* considered. Default value is 1000.
*/
public void setMinLinesPerReorg(int minLinesPerReorg);
/**
* Returns the transaction log threshold which is the minimum size of the
* transaction log (T?.txt) in bytes, before which the contents of the log
* are copied to V?.txt and E?.txt. Default value is 4MB.
*/
public long getTxLogThreshold();
/**
* Modify the transaction log threshold. A higher number indicates fewer
* file operations, but more disk space and startup time in the worst case.
* Default value is 4MB.
*/
public void setTxLogThreshold(long txLogThreshold);
/** This method flushes the transaction log to the V/E text files */
public void flushTxLog();
/** This method backs up the database while it is still operational. Only one backup can be in progress at a time.
*
* @param pathToDir directory to which the database must be backed up.
*/
public void backup(String pathToDir);
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyGraphSONModule.java
================================================
// Copyright 2017 JanusGraph Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.store.EdgeBean;
import com.lambdazen.bitsy.store.VertexBean;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.tinkerpop.gremlin.structure.io.graphson.TinkerPopJacksonModule;
import org.apache.tinkerpop.shaded.jackson.core.*;
import org.apache.tinkerpop.shaded.jackson.core.type.WritableTypeId;
import org.apache.tinkerpop.shaded.jackson.databind.DeserializationContext;
import org.apache.tinkerpop.shaded.jackson.databind.SerializerProvider;
import org.apache.tinkerpop.shaded.jackson.databind.deser.std.StdDeserializer;
import org.apache.tinkerpop.shaded.jackson.databind.jsontype.TypeSerializer;
import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdSerializer;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class BitsyGraphSONModule extends TinkerPopJacksonModule {
private static final String TYPE_NAMESPACE = "bitsy";
private static final Map TYPE_DEFINITIONS =
Collections.unmodifiableMap(new LinkedHashMap() {
{
put(UUID.class, "UUID");
put(VertexBean.class, "VertexBean");
put(EdgeBean.class, "EdgeBean");
}
});
private BitsyGraphSONModule() {
super("bitsy");
addSerializer(UUID.class, new UUIDSerializer());
addDeserializer(UUID.class, new UUIDDeserializer());
// addSerializer(VertexBean.class, new UUIDSerializer());
// addSerializer(EdgeBean.class, new UUIDSerializer());
}
private static final BitsyGraphSONModule INSTANCE = new BitsyGraphSONModule();
public static final BitsyGraphSONModule getInstance() {
return INSTANCE;
}
@Override
public Map getTypeDefinitions() {
return TYPE_DEFINITIONS;
}
@Override
public String getTypeNamespace() {
return TYPE_NAMESPACE;
}
public static class UUIDSerializer extends StdSerializer {
public UUIDSerializer() {
super(UUID.class);
}
@Override
public void serialize(
final UUID uuid, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException, JsonGenerationException {
String uuidStr = UUID.toString(uuid);
jsonGenerator.writeString(uuidStr);
}
@Override
public void serializeWithType(
final UUID uuid,
final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider,
final TypeSerializer typeSerializer)
throws IOException, JsonProcessingException {
// since jackson 2.9, must keep track of `typeIdDef` in order to close it properly
final WritableTypeId typeIdDef =
typeSerializer.writeTypePrefix(jsonGenerator, typeSerializer.typeId(uuid, JsonToken.VALUE_STRING));
String uuidStr = UUID.toString(uuid);
jsonGenerator.writeString(uuidStr);
typeSerializer.writeTypeSuffix(jsonGenerator, typeIdDef);
}
}
public static class UUIDDeserializer extends StdDeserializer {
public UUIDDeserializer() {
super(UUID.class);
}
@Override
public UUID deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
jsonParser.nextToken();
final String uuidStr = deserializationContext.readValue(jsonParser, String.class);
return UUID.fromString(uuidStr);
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyIoRegistryV3d0.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.store.EdgeBean;
import com.lambdazen.bitsy.store.VertexBean;
import org.apache.tinkerpop.gremlin.structure.io.AbstractIoRegistry;
import org.apache.tinkerpop.gremlin.structure.io.binary.GraphBinaryIo;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONIo;
import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoIo;
import org.apache.tinkerpop.shaded.kryo.Kryo;
import org.apache.tinkerpop.shaded.kryo.Serializer;
import org.apache.tinkerpop.shaded.kryo.io.Input;
import org.apache.tinkerpop.shaded.kryo.io.Output;
public class BitsyIoRegistryV3d0 extends AbstractIoRegistry {
private static final BitsyIoRegistryV3d0 INSTANCE = new BitsyIoRegistryV3d0();
private BitsyIoRegistryV3d0() {
register(GryoIo.class, UUID.class, new UUIDGryoSerializer());
register(GryoIo.class, VertexBean.class, new UUIDGryoSerializer());
register(GryoIo.class, EdgeBean.class, new UUIDGryoSerializer());
register(GraphSONIo.class, UUID.class, BitsyGraphSONModule.getInstance());
register(GraphSONIo.class, VertexBean.class, BitsyGraphSONModule.getInstance());
register(GraphSONIo.class, EdgeBean.class, BitsyGraphSONModule.getInstance());
register(GraphBinaryIo.class, UUID.class, new UUIDGraphBinarySerializer());
register(GraphBinaryIo.class, VertexBean.class, new UUIDGraphBinarySerializer());
register(GraphBinaryIo.class, EdgeBean.class, new UUIDGraphBinarySerializer());
}
public static BitsyIoRegistryV3d0 instance() {
return INSTANCE;
}
static final class UUIDGryoSerializer extends Serializer {
@Override
public void write(final Kryo kryo, final Output output, final UUID uuid) {
output.writeLong(uuid.getMostSignificantBits());
output.writeLong(uuid.getLeastSignificantBits());
}
@Override
public UUID read(final Kryo kryo, final Input input, final Class aClass) {
long msb = input.readLong();
long lsb = input.readLong();
return new UUID(msb, lsb);
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyIsolationLevel.java
================================================
package com.lambdazen.bitsy;
public enum BitsyIsolationLevel {
READ_COMMITTED, // default
REPEATABLE_READ
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyProperty.java
================================================
package com.lambdazen.bitsy;
import java.util.NoSuchElementException;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
public class BitsyProperty implements Property {
BitsyElement element;
String key;
T value;
boolean removed = false;
public BitsyProperty(BitsyElement element, String key, T value) {
this.element = element;
this.key = key;
this.value = value;
}
@Override
public String key() {
return key;
}
@Override
public T value() throws NoSuchElementException {
if (removed) {
throw new NoSuchElementException("This property is empty");
} else {
return value;
}
}
@Override
public boolean isPresent() {
return !removed;
}
@Override
public Element element() {
return element;
}
@Override
public void remove() {
if (isPresent()) {
element.removeProperty(key);
this.removed = true;
}
}
// Moved to ElementHelper hashCode and equals in TP3
@Override
public int hashCode() {
return ElementHelper.hashCode(this);
}
@Override
public boolean equals(final Object object) {
return ElementHelper.areEqual(this, object);
}
public String toString() {
return StringFactory.propertyString(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyRetryException.java
================================================
package com.lambdazen.bitsy;
public class BitsyRetryException extends BitsyException {
private static final long serialVersionUID = 976641612846833462L;
BitsyErrorCodes code;
public BitsyRetryException(BitsyErrorCodes code) {
super(code);
}
public BitsyRetryException(BitsyErrorCodes code, String s) {
super(code, s);
}
public BitsyRetryException(BitsyErrorCodes code, String s, Throwable t) {
super(code, s, t);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyState.java
================================================
package com.lambdazen.bitsy;
public enum BitsyState {
U, // unmodified
M, // modified
D // deleted
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyVertex.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.ads.dict.Dictionary;
import com.lambdazen.bitsy.store.IStringCanonicalizer;
import com.lambdazen.bitsy.store.VertexBean;
import com.lambdazen.bitsy.store.VertexBeanJson;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
public class BitsyVertex extends BitsyElement implements Vertex {
private static final Direction[] directions = new Direction[] {Direction.OUT, Direction.IN};
public BitsyVertex(
UUID id, String label, Dictionary properties, BitsyTransaction tx, BitsyState state, int version) {
super(id, label, properties, tx, state, version);
}
public BitsyVertex(VertexBean bean, BitsyTransaction tx, BitsyState state) {
this(bean.getId(), bean.getLabel(), bean.getPropertiesDict(), tx, state, bean.getVersion());
}
@Override
public String label() {
String result = super.label();
return (result == null) ? Vertex.DEFAULT_LABEL : result;
}
@Override
public Iterator edges(Direction dir, String... edgeLabels) {
return tx.getEdges(this, dir, edgeLabels).iterator();
}
public VertexBean asBean() {
// The TX is usually not active at this point. So no checks.
return new VertexBean((UUID) id, label, properties, version);
}
public VertexBean asBean(IStringCanonicalizer canonicalizer) {
if (properties != null) {
properties.canonicalizeKeys(canonicalizer);
}
return asBean();
}
public VertexBeanJson asJsonBean() {
// The TX is usually not active at this point. So no checks.
// TreeMap propertyMap = (properties == null) ? null : properties.toMap();
return new VertexBeanJson((UUID) id, label, properties, version, state);
}
@Override
public Iterator vertices(final Direction dir, String... edgeLabels) {
final ArrayList vertices = new ArrayList();
for (Direction myDir : directions) {
if ((myDir == dir) || (dir == Direction.BOTH)) {
Iterator iter = edges(myDir, edgeLabels);
while (iter.hasNext()) {
Edge e = iter.next();
Vertex toAdd = (myDir.opposite() == Direction.IN) ? e.inVertex() : e.outVertex();
vertices.add(toAdd);
}
}
}
// Go through the edges and load the vertices
return vertices.iterator();
}
public void incrementVersion() {
// It is OK for the version to wrap around MAX_INT
this.version++;
}
public void remove() {
tx.removeVertex(this);
}
@Override
public Edge addEdge(String label, Vertex inVertex, Object... keyValues) {
if (keyValues.length % 2 == 1) {
throw new IllegalArgumentException(
"Expecting even number of items in the keyValue array. Found " + keyValues.length);
}
if (label == null) {
throw new IllegalArgumentException("You have to specify a non-null String label when adding an edge");
} else if (label.length() == 0) {
throw new IllegalArgumentException("You have to specify a non-empty String label when adding an edge");
} else if (label.charAt(0) == '~') {
throw new IllegalArgumentException("Labels beginning with ~ are invalid");
}
if (inVertex == null) {
throw new IllegalArgumentException("The inVertex supplied to addEdge() is null");
}
// Validate first
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] == T.label) {
throw new UnsupportedOperationException("Encountered T.label in addVertex");
} else if (keyValues[i] == T.id) {
throw new UnsupportedOperationException(
"Encountered T.id in addVertex", new BitsyException(BitsyErrorCodes.NO_CUSTOM_ID_SUPPORT));
} else if (keyValues[i] == null) {
throw new IllegalArgumentException("Encountered a null key in argument #" + i);
} else if (keyValues[i + 1] == null) {
throw new IllegalArgumentException("Encountered a null value in argument #" + i);
} else if (!(keyValues[i] instanceof String)) {
throw new IllegalArgumentException(
"Encountered a non-string key: " + keyValues[i] + " in argument #" + i);
}
}
// Construct the edge with this as the out vertex
BitsyEdge edge =
new BitsyEdge(UUID.randomUUID(), null, tx, BitsyState.M, 0, label, (UUID) id(), (UUID) inVertex.id());
for (int i = 0; i < keyValues.length; i = i + 2) {
String key = (String) keyValues[i];
edge.property(key, keyValues[i + 1]);
}
tx.addEdge(edge);
return edge;
}
public String toString() {
return StringFactory.vertexString(this);
}
// THERE ARE TWO MORE COPIES OF THIS CODE IN ELEMENT AND EDGE
@Override
public VertexProperty property(String key) {
T value = value(key);
if (value == null) {
return VertexProperty.empty();
} else {
return new BitsyVertexProperty(this, key, value);
}
}
@Override
public VertexProperty property(String key, V value) {
super.property(key, value);
return new BitsyVertexProperty(this, key, value);
}
@Override
public VertexProperty property(
final VertexProperty.Cardinality cardinality, final String key, final V value, final Object... keyValues) {
if (cardinality != Cardinality.single) {
// For some reason, TP3 tests fail with this exception
// throw new BitsyException(BitsyErrorCodes.NO_MULTI_PROPERTY_SUPPORT, "Encountered cardinality: " +
// cardinality.toString());
} else if (keyValues.length != 0) {
throw new UnsupportedOperationException(
"Encountered key values: " + keyValues.toString(),
new BitsyException(BitsyErrorCodes.NO_META_PROPERTY_SUPPORT));
}
return property(key, value);
}
// THERE ARE TWO MORE COPIES OF THIS CODE IN ELEMENT AND EDGE
@Override
public Iterator> properties(String... propertyKeys) {
ArrayList> ans = new ArrayList>();
if (propertyKeys.length == 0) {
if (this.properties == null) return Collections.emptyIterator();
propertyKeys = this.properties.getPropertyKeys();
}
for (String key : propertyKeys) {
VertexProperty prop = property(key);
if (prop.isPresent()) ans.add(prop);
}
return ans.iterator();
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/BitsyVertexProperty.java
================================================
package com.lambdazen.bitsy;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
public class BitsyVertexProperty extends BitsyProperty implements VertexProperty {
public BitsyVertexProperty(final BitsyVertex vertex, final String key, final V value) {
super(vertex, key, value);
}
@Override
public Set keys() {
return Collections.emptySet();
}
@Override
public Property property(final String key) {
throw new BitsyException(BitsyErrorCodes.NO_META_PROPERTY_SUPPORT);
}
@Override
public Property property(final String key, final U value) {
throw new BitsyException(BitsyErrorCodes.NO_META_PROPERTY_SUPPORT);
}
@Override
public Vertex element() {
return (BitsyVertex) super.element();
}
@Override
public Iterator> properties(final String... propertyKeys) {
throw new BitsyException(BitsyErrorCodes.NO_META_PROPERTY_SUPPORT);
}
@Override
public Object id() {
return element().id().toString() + ":" + key();
}
public String toString() {
return StringFactory.propertyString(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ICommitChanges.java
================================================
package com.lambdazen.bitsy;
import java.util.Collection;
public interface ICommitChanges {
public Collection getVertexChanges();
public Collection getEdgeChanges();
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/IEdge.java
================================================
package com.lambdazen.bitsy;
public interface IEdge {
public UUID getInVertexId();
public UUID getOutVertexId();
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/IGraphStore.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.store.EdgeBean;
import com.lambdazen.bitsy.store.VertexBean;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Element;
public interface IGraphStore {
public void commit(ICommitChanges changes);
/** Only to be used internally within the store */
public VertexBean getVertex(UUID id);
/** Returns a transaction-specific BitsyVertex given the tx and the ID */
public BitsyVertex getBitsyVertex(BitsyTransaction tx, UUID id);
/** Only to be used internally within the store */
public EdgeBean getEdge(UUID id);
/** Returns a transaction-specific BitsyEdge given the tx and the ID */
public BitsyEdge getBitsyEdge(BitsyTransaction tx, UUID id);
public List getEdges(UUID vertexId, Direction dir, String[] edgeLabels);
public Collection getAllVertices();
public Collection getAllEdges();
public void createKeyIndex(String key, Class elementType);
public void dropKeyIndex(String key, Class elementType);
public Set getIndexedKeys(Class elementType);
public void shutdown();
public Collection lookupVertices(String key, Object value);
public Collection lookupEdges(String key, Object value);
public boolean allowFullGraphScans();
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ITransaction.java
================================================
package com.lambdazen.bitsy;
import java.util.Iterator;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
public interface ITransaction extends Transaction {
public void save(boolean commit);
public void validateForQuery(BitsyElement bitsyElement) throws BitsyException;
public Vertex getVertex(UUID outVertexId) throws BitsyException;
public Edge getEdge(UUID id) throws BitsyException;
public Iterable getEdges(BitsyVertex bitsyVertex, Direction dir, String... edgeLabels) throws BitsyException;
public void markForPropertyUpdate(BitsyElement bitsyElement) throws BitsyException;
public void addVertex(BitsyVertex vertex) throws BitsyException;
public void removeVertex(BitsyVertex vertex) throws BitsyException;
public void addEdge(BitsyEdge edge) throws BitsyException;
public void removeEdge(BitsyEdge edge) throws BitsyException;
public Iterator getAllVertices();
public Iterator getAllEdges();
public Iterator lookupVertices(String key, Object value);
public Iterator lookupEdges(String key, Object value);
public BitsyIsolationLevel getIsolationLevel();
public void setIsolationLevel(BitsyIsolationLevel level);
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/PortDatabase.java
================================================
package com.lambdazen.bitsy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** This class ports the database files across major versions */
public class PortDatabase {
public static final List SUPPORTED_VERSIONS = Arrays.asList(new String[] {"1.0", "1.5"});
private static final String[] FILE_NAMES =
new String[] {"metaA.txt", "metaB.txt", "vA.txt", "vB.txt", "eA.txt", "eB.txt", "txA.txt", "txB.txt"};
private static final Charset UTF8 = Charset.forName("UTF-8");
String targetVersion;
Path sourcePath;
Path targetPath;
String sourceVersion;
String error = null;
public PortDatabase(String[] args) throws IOException {
if (args.length == 0) {
setError("No arguments provided");
return;
} else if (args.length != 4) {
setError("Expecting 4 arguments");
return;
}
this.targetVersion = null;
int i;
for (i = 0; i < args.length - 1; i++) {
if (args[i].equals("-toVersion")) {
targetVersion = args[i + 1];
break;
}
}
String sourceDir = (i == 0) ? args[2] : args[0];
String targetDir = (i == 2) ? args[1] : args[3];
if (targetVersion == null) {
setError("Could not find -toVersion flag followed by a version number");
return;
} else if (!SUPPORTED_VERSIONS.contains(targetVersion)) {
setError("The version number " + targetVersion
+ " provided in the -toVersion flag is not supported. You must provide one of the following: "
+ SUPPORTED_VERSIONS);
return;
}
this.sourcePath = Paths.get(sourceDir);
this.targetPath = Paths.get(targetDir);
if (!Files.isDirectory(sourcePath)) {
setError("Source path " + sourceDir + " does not point to a directory");
return;
}
if (!Files.isDirectory(targetPath)) {
setError("Target path " + targetDir + " does not point to a directory");
return;
}
this.sourceVersion = getVersion(sourcePath);
if (sourceVersion == null) {
return;
}
if (!SUPPORTED_VERSIONS.contains(sourceVersion)) {
setError("The version number " + sourceVersion
+ " found in the source database is not supported. You must provide a database created by one of these versions of Bitsy: "
+ SUPPORTED_VERSIONS);
return;
}
if (sourceVersion.equals(targetVersion)) {
setError("The source and target version numbers are the same: Version " + sourceVersion);
return;
}
System.out.println("Porting database in " + sourceDir + " from version " + sourceVersion + " to version "
+ targetVersion + " under " + targetDir);
portDatabase();
System.out.println("Success");
}
private void portDatabase() throws IOException {
Converter converter;
if (sourceVersion.equals("1.0") && targetVersion.equals("1.5")) {
converter = new V10ToV15Coverter();
} else if (sourceVersion.equals("1.5") && targetVersion.equals("1.0")) {
converter = new V15ToV10Coverter();
} else {
setError("PortDatabase does not support porting from source version " + sourceVersion
+ " to target version " + targetVersion);
return;
}
for (String fileName : FILE_NAMES) {
Path path = sourcePath.resolve(fileName);
InputStream fis = null;
BufferedReader br = null;
OutputStream fos = null;
try {
fis = Files.newInputStream(path);
fos = Files.newOutputStream(targetPath.resolve(fileName));
br = new BufferedReader(new InputStreamReader(fis, UTF8));
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
String outLine = converter.convert(line, lineNo, fileName);
if (outLine != null) {
fos.write(outLine.getBytes(UTF8));
fos.write('\n');
}
}
} finally {
if (br != null) {
br.close();
}
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
}
}
private String getVersion(Path sourcePath) throws IOException {
Path mA = sourcePath.resolve("metaA.txt");
Path mB = sourcePath.resolve("metaB.txt");
String version = "1.0";
boolean missingFiles = true;
if (Files.exists(mA)) {
String versionA = getVersionFromPath(mA);
if (versionA != null) {
version = versionA;
}
missingFiles = false;
}
if (Files.exists(mB)) {
String versionB = getVersionFromPath(mB);
if (versionB != null) {
version = versionB;
}
missingFiles = false;
}
if (missingFiles) {
setError("Neither metaA.txt nor metaB.txt can be found in " + sourcePath);
return null;
} else {
return version;
}
}
public String getVersionFromPath(Path metaPath) throws IOException {
String fileName = metaPath.toString();
try (BufferedReader br = Files.newBufferedReader(metaPath, StandardCharsets.UTF_8)) {
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
lineNo++;
int hashPos = line.lastIndexOf('#');
if (hashPos < 0) {
throw new BitsyException(
BitsyErrorCodes.CHECKSUM_MISMATCH,
"Line " + lineNo + " in file " + fileName + " has no hash-code. Encountered " + line);
} else {
String hashCode = line.substring(hashPos + 1);
String expHashCode = toHex(line.substring(0, hashPos + 1).hashCode());
if (!hashCode.endsWith(expHashCode)) {
throw new BitsyException(
BitsyErrorCodes.CHECKSUM_MISMATCH,
"Line " + lineNo + " in file " + fileName + " has the wrong hash-code " + hashCode
+ ". Expected " + expHashCode);
} else {
// All OK
char typeChar = line.charAt(0);
String version = line.substring(2, hashPos);
if (typeChar == 'M') {
return version;
}
}
}
}
}
return null;
}
private void setError(String error) {
this.error = error;
}
private String getError() {
return error;
}
private static void printUsage(String error) {
if (error != null) {
System.err.println("ERROR: " + error);
}
System.err.println(
"Usage: java com.lambdazen.bitsy.PortDatabase -toVersion ");
}
public static void main(String[] args) {
try {
PortDatabase task = new PortDatabase(args);
if (task.getError() != null) {
printUsage(task.getError());
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
// Faster than Integer.toHexString()
private static final char[] HEX_CHAR_ARR = "0123456789abcdef".toCharArray();
private static String toHex(int input) {
final char[] sb = new char[8];
final int len = (sb.length - 1);
for (int i = 0; i <= len; i++) { // MSB
sb[i] = HEX_CHAR_ARR[((int) (input >>> ((len - i) << 2))) & 0xF];
}
return new String(sb);
}
public interface Converter {
public String convert(String line, int lineNo, String fileName);
}
public class V10ToV15Coverter implements Converter {
Pattern edgePat = Pattern.compile("^(E=\\{[^{}]*,\"p\":)\\[\"java.util.TreeMap\",(.*)\\]\\}#[0-9a-zA-Z]*$");
@Override
public String convert(String line, int lineNo, String fileName) {
if (line.startsWith("H=") && fileName.startsWith("meta")) {
String versionLine = "M=1.5#";
return line + "\n" + versionLine + toHex(versionLine.hashCode());
} else if (line.startsWith("E=")) {
Matcher m = edgePat.matcher(line);
if (!m.find()) {
return line;
} else {
// Move from TreeMap to Map
line = m.group(1) + m.group(2) + "}#";
return line + toHex(line.hashCode());
}
} else {
return line;
}
}
}
public class V15ToV10Coverter implements Converter {
Pattern edgePat = Pattern.compile("^(E=\\{[^{}]*,\"p\":)(.*)\\}#[0-9a-zA-Z]*$");
@Override
public String convert(String line, int lineNo, String fileName) {
if (line.startsWith("M=") && fileName.startsWith("meta")) {
// Skip the version
return null;
} else if (line.startsWith("E=")) {
Matcher m = edgePat.matcher(line);
if (!m.find()) {
return line;
} else {
// Move from TreeMap to Map
line = m.group(1) + "[\"java.util.TreeMap\"," + m.group(2) + "]}#";
return line + toHex(line.hashCode());
}
} else {
return line;
}
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ThreadedBitsyGraph.java
================================================
package com.lambdazen.bitsy;
import com.lambdazen.bitsy.tx.BitsyTransaction;
import com.lambdazen.bitsy.tx.BitsyTransactionContext;
public class ThreadedBitsyGraph extends BitsyGraph {
BitsyGraph underlyingGraph;
BitsyTransaction tx;
public ThreadedBitsyGraph(BitsyGraph g) {
// Using protected constructor that doesn't create a graph store
super('_', g.isFullGraphScanAllowed());
this.underlyingGraph = g;
this.tx = null;
}
public String toString() {
return underlyingGraph.toString();
}
@Override
public Features features() {
return underlyingGraph.features();
}
@Override
protected BitsyTransaction getTx() {
// Overriding the getTx() method ensures that the work will be done on
// the local transaction, NOT the ThreadLocal transaction
if ((tx == null) || (!tx.isOpen())) {
this.tx = new BitsyTransaction(
new BitsyTransactionContext(underlyingGraph.getStore()),
getDefaultIsolationLevel(),
underlyingGraph);
}
return tx;
}
@Override
/** This method can be used to check if the current threaded-graph is actively executing a transaction */
public boolean isTransactionActive() {
return (tx != null);
}
public BitsyIsolationLevel getDefaultIsolationLevel() {
return underlyingGraph.getDefaultIsolationLevel();
}
public void setDefaultIsolationLevel(BitsyIsolationLevel level) {
underlyingGraph.setDefaultIsolationLevel(level);
}
public BitsyIsolationLevel getTxIsolationLevel() {
return getTx().getIsolationLevel();
}
public void setTxIsolationLevel(BitsyIsolationLevel level) {
getTx().setIsolationLevel(level);
}
@Override
public void shutdown() {
// As per Blueprints tests, shutdown() implies automatic commit
if (tx == null) {
// Nothing to do
} else {
try {
// Stop the old transaction if it exists
tx.commit();
} finally {
// Remove this transaction -- independent of success/failure
this.tx = null;
}
}
// Don't mess with the graph store -- this is only a ThreadedGraph, not the main one
}
// @Deprecated
// public void stopTransaction(Conclusion conclusion) {
// stopTx(conclusion == Conclusion.SUCCESS);
// }
// @Override
// public void commit() {
// tx.save(commit);
// }
//
// @Override
// public void rollback() {
// stopTx(false);
// }
//
// public void stopTx(boolean commit) {
// if (tx == null) {
// // Nothing to do
// } else {
// try {
// // Stop the old transaction if it exists
// tx.save(commit);
// } finally {
// // Remove this transaction -- independent of success/failure
// this.tx = null;
// }
// }
// }
//
// @Override
// public TransactionalGraph startTransaction() {
// throw new UnsupportedOperationException("Can not startTransaction on a threaded transaction graph");
// }
//
// @Override
// public void shutdown() {
// // As per Blueprints tests, shutdown() implies automatic commit
// stopTx(true);
//
// // Don't mess with the graph store -- this is only a ThreadedGraph, not the main one
// }
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/UUID.java
================================================
package com.lambdazen.bitsy;
import com.fasterxml.jackson.annotation.JsonIgnore;
/** This class captures a UUID and is modeled after java.util.UUID */
public class UUID implements Comparable {
// Java guarantees that
// "Reads and writes are atomic for reference variables and for most primitive variables (all types except long and
// double)."
// Therefore, mostSigBits and leastSigBits must not be changed during the lifetime of this object.
// Also, these objects must not be accessible to other threads without a memory flush/fence/barrier
// Typically this memory barrier is handled by the ConcurrentHashMap that holds the vertex/edge bean.
private final long mostSigBits;
private final long leastSigBits;
public UUID(long msb, long lsb) {
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
@JsonIgnore
public long getMostSignificantBits() {
return mostSigBits;
}
@JsonIgnore
public long getLeastSignificantBits() {
return leastSigBits;
}
public String toString() {
return uuidRepr();
}
public String uuidRepr() {
return new java.util.UUID(mostSigBits, leastSigBits).toString();
}
public static UUID fromString(String str) {
java.util.UUID ans = java.util.UUID.fromString(str);
return new UUID(ans.getMostSignificantBits(), ans.getLeastSignificantBits());
}
public static UUID randomUUID() {
java.util.UUID ans = java.util.UUID.randomUUID();
return new UUID(ans.getMostSignificantBits(), ans.getLeastSignificantBits());
}
public int compareTo(UUID other) {
if (this.mostSigBits < other.mostSigBits) {
return -1;
} else if (this.mostSigBits > other.mostSigBits) {
return 1;
} else if (this.leastSigBits < other.leastSigBits) {
return -1;
} else if (this.leastSigBits > other.leastSigBits) {
return 1;
} else {
return 0;
}
}
@Override
public int hashCode() {
// Same as java.util.UUID
long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (this == obj) {
return true;
} else {
try {
UUID other = (UUID) obj;
return (mostSigBits == other.getMostSignificantBits())
&& (leastSigBits == other.getLeastSignificantBits());
} catch (ClassCastException e) {
return false;
}
}
}
public static String toString(UUID obj) {
return new java.util.UUID(obj.getMostSignificantBits(), obj.getLeastSignificantBits()).toString();
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/UUIDGraphBinarySerializer.java
================================================
package com.lambdazen.bitsy;
import java.io.IOException;
import org.apache.tinkerpop.gremlin.structure.io.Buffer;
import org.apache.tinkerpop.gremlin.structure.io.binary.DataType;
import org.apache.tinkerpop.gremlin.structure.io.binary.GraphBinaryReader;
import org.apache.tinkerpop.gremlin.structure.io.binary.GraphBinaryWriter;
import org.apache.tinkerpop.gremlin.structure.io.binary.types.CustomTypeSerializer;
public class UUIDGraphBinarySerializer implements CustomTypeSerializer {
private final byte[] typeInfoBuffer = new byte[] {0, 0, 0, 0};
@Override
public String getTypeName() {
return "bitsy.UUID";
}
@Override
public DataType getDataType() {
return DataType.CUSTOM;
}
@Override
public UUID read(Buffer buffer, GraphBinaryReader context) throws IOException {
// {custom type info}, {value_flag} and {value}
// No custom_type_info
if (buffer.readInt() != 0) {
throw new IOException("{custom_type_info} should not be provided for this custom type");
}
return readValue(buffer, context, true);
}
@Override
public UUID readValue(Buffer buffer, GraphBinaryReader context, boolean nullable) throws IOException {
if (nullable) {
final byte valueFlag = buffer.readByte();
if ((valueFlag & 1) == 1) {
return null;
}
}
// Read the byte length of the value bytes
final int valueLength = buffer.readInt();
if (valueLength <= 0) {
throw new IOException(String.format("Unexpected value length: %d", valueLength));
}
if (valueLength > buffer.readableBytes()) {
throw new IOException(
String.format("Not enough readable bytes: %d (expected %d)", valueLength, buffer.readableBytes()));
}
long msb = context.readValue(buffer, Long.class, false);
long lsb = context.readValue(buffer, Long.class, false);
return new UUID(msb, lsb);
}
@Override
public void write(UUID value, Buffer buffer, GraphBinaryWriter context) throws IOException {
// Write {custom type info}, {value_flag} and {value}
buffer.writeBytes(typeInfoBuffer);
writeValue(value, buffer, context, true);
}
@Override
public void writeValue(UUID value, Buffer buffer, GraphBinaryWriter context, boolean nullable) throws IOException {
if (value == null) {
if (!nullable) {
throw new IOException("Unexpected null value when nullable is false");
}
context.writeValueFlagNull(buffer);
return;
}
if (nullable) {
context.writeValueFlagNone(buffer);
}
final Long msb = value.getMostSignificantBits();
final Long lsb = value.getLeastSignificantBits();
// value_length = name_byte_length + long + long
buffer.writeInt(4 + 8 + 8);
context.writeValue(msb, buffer, false);
context.writeValue(lsb, buffer, false);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary.java
================================================
package com.lambdazen.bitsy.ads.dict;
import com.lambdazen.bitsy.store.IStringCanonicalizer;
/**
* This is an re-organizing (not immutable) map from String to Object. The set
* and remove methods return a reference to a new map with the value.
*/
public interface Dictionary {
public int size();
public Object getProperty(String key);
public String[] getPropertyKeys();
public Dictionary setProperty(String key, Object value);
public Dictionary removeProperty(String key);
public Dictionary copyOf();
// public TreeMap toMap();
public void canonicalizeKeys(IStringCanonicalizer canonicalizer);
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary1.java
================================================
package com.lambdazen.bitsy.ads.dict;
/** This class implements a dictionary with one element */
public class Dictionary1 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 1;
String key0;
Object value0;
// Expand constructor
public Dictionary1(String key, Object value) {
this.key0 = key;
this.value0 = value;
}
// Contract constructor
public Dictionary1(Dictionary2 base) {
this.key0 = base.key0;
this.value0 = base.value0;
}
// Copy constructor
public Dictionary1(Dictionary1 base) {
this.key0 = base.key0;
this.value0 = base.value0;
}
@Override
protected String[] keys() {
return new String[] {key0};
}
@Override
protected Object[] values() {
return new Object[] {value0};
}
@Override
public Dictionary copyOf() {
return new Dictionary1(this);
}
protected int contractThreshold() {
return 0;
}
protected Dictionary contract() {
return null;
}
protected Dictionary expand(String key, Object value) {
return new Dictionary2(this, key, value);
}
protected void write(int index, String key, Object value) {
key0 = key;
value0 = value;
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary11.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary11 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 11;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
String key3;
Object value3;
String key4;
Object value4;
String key5;
Object value5;
String key6;
Object value6;
String key7;
Object value7;
String key8;
Object value8;
String key9;
Object value9;
String key10;
Object value10;
// Expand constructor
public Dictionary11(Dictionary8 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
// Last key
this.key8 = key;
this.value8 = value;
}
// Contract constructor
public Dictionary11(Dictionary16 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
this.key8 = base.key8;
this.value8 = base.value8;
this.key9 = base.key9;
this.value9 = base.value9;
this.key10 = base.key10;
this.value10 = base.value10;
}
// Copy constructor
public Dictionary11(Dictionary11 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
this.key8 = base.key8;
this.value8 = base.value8;
this.key9 = base.key9;
this.value9 = base.value9;
this.key10 = base.key10;
this.value10 = base.value10;
}
// FromMap constructor
public Dictionary11(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
this.key3 = lookupKey(keys, 3);
this.value3 = lookupValue(values, 3);
this.key4 = lookupKey(keys, 4);
this.value4 = lookupValue(values, 4);
this.key5 = lookupKey(keys, 5);
this.value5 = lookupValue(values, 5);
this.key6 = lookupKey(keys, 6);
this.value6 = lookupValue(values, 6);
this.key7 = lookupKey(keys, 7);
this.value7 = lookupValue(values, 7);
this.key8 = lookupKey(keys, 8);
this.value8 = lookupValue(values, 8);
this.key9 = lookupKey(keys, 9);
this.value9 = lookupValue(values, 9);
this.key10 = lookupKey(keys, 10);
this.value10 = lookupValue(values, 10);
}
@Override
String[] keys() {
return new String[] {key0, key1, key2, key3, key4, key5, key6, key7, key8, key9, key10};
}
@Override
Object[] values() {
return new Object[] {value0, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10};
}
@Override
void write(int index, String key, Object value) {
if (index < 6) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
case 3:
key3 = key;
value3 = value;
break;
case 4:
key4 = key;
value4 = value;
break;
case 5:
key5 = key;
value5 = value;
break;
default:
throw new RuntimeException("Bug in code");
}
} else {
switch (index) {
case 6:
key6 = key;
value6 = value;
break;
case 7:
key7 = key;
value7 = value;
break;
case 8:
key8 = key;
value8 = value;
break;
case 9:
key9 = key;
value9 = value;
break;
case 10:
key10 = key;
value10 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary16(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary8.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary8(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary11(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary16.java
================================================
package com.lambdazen.bitsy.ads.dict;
import java.util.Arrays;
public class Dictionary16 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 16;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
String key3;
Object value3;
String key4;
Object value4;
String key5;
Object value5;
String key6;
Object value6;
String key7;
Object value7;
String key8;
Object value8;
String key9;
Object value9;
String key10;
Object value10;
String key11;
Object value11;
String key12;
Object value12;
String key13;
Object value13;
String key14;
Object value14;
String key15;
Object value15;
// Expand constructor
public Dictionary16(Dictionary11 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
this.key8 = base.key8;
this.value8 = base.value8;
this.key9 = base.key9;
this.value9 = base.value9;
this.key10 = base.key10;
this.value10 = base.value10;
// Last key
this.key11 = key;
this.value11 = value;
}
// Contract constructor
public Dictionary16(DictionaryMax base) {
String[] keys = Arrays.copyOf(base.keys(), 16);
Object[] values = Arrays.copyOf(base.values(), 16);
this.key0 = keys[0];
this.value0 = values[0];
this.key1 = keys[1];
this.value1 = values[1];
this.key2 = keys[2];
this.value2 = values[2];
this.key3 = keys[3];
this.value3 = values[3];
this.key4 = keys[4];
this.value4 = values[4];
this.key5 = keys[5];
this.value5 = values[5];
this.key6 = keys[6];
this.value6 = values[6];
this.key7 = keys[7];
this.value7 = values[7];
this.key8 = keys[8];
this.value8 = values[8];
this.key9 = keys[9];
this.value9 = values[9];
this.key10 = keys[10];
this.value10 = values[10];
this.key11 = keys[11];
this.value11 = values[11];
this.key12 = keys[12];
this.value12 = values[12];
this.key13 = keys[13];
this.value13 = values[13];
this.key14 = keys[14];
this.value14 = values[14];
this.key15 = keys[15];
this.value15 = values[15];
}
// Copy constructor
public Dictionary16(Dictionary16 base) {
String[] keys = Arrays.copyOf(base.keys(), 16);
Object[] values = Arrays.copyOf(base.values(), 16);
this.key0 = keys[0];
this.value0 = values[0];
this.key1 = keys[1];
this.value1 = values[1];
this.key2 = keys[2];
this.value2 = values[2];
this.key3 = keys[3];
this.value3 = values[3];
this.key4 = keys[4];
this.value4 = values[4];
this.key5 = keys[5];
this.value5 = values[5];
this.key6 = keys[6];
this.value6 = values[6];
this.key7 = keys[7];
this.value7 = values[7];
this.key8 = keys[8];
this.value8 = values[8];
this.key9 = keys[9];
this.value9 = values[9];
this.key10 = keys[10];
this.value10 = values[10];
this.key11 = keys[11];
this.value11 = values[11];
this.key12 = keys[12];
this.value12 = values[12];
this.key13 = keys[13];
this.value13 = values[13];
this.key14 = keys[14];
this.value14 = values[14];
this.key15 = keys[15];
this.value15 = values[15];
}
// FromMap constructor
public Dictionary16(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
this.key3 = lookupKey(keys, 3);
this.value3 = lookupValue(values, 3);
this.key4 = lookupKey(keys, 4);
this.value4 = lookupValue(values, 4);
this.key5 = lookupKey(keys, 5);
this.value5 = lookupValue(values, 5);
this.key6 = lookupKey(keys, 6);
this.value6 = lookupValue(values, 6);
this.key7 = lookupKey(keys, 7);
this.value7 = lookupValue(values, 7);
this.key8 = lookupKey(keys, 8);
this.value8 = lookupValue(values, 8);
this.key9 = lookupKey(keys, 9);
this.value9 = lookupValue(values, 9);
this.key10 = lookupKey(keys, 10);
this.value10 = lookupValue(values, 10);
this.key11 = lookupKey(keys, 11);
this.value11 = lookupValue(values, 11);
this.key12 = lookupKey(keys, 12);
this.value12 = lookupValue(values, 12);
this.key13 = lookupKey(keys, 13);
this.value13 = lookupValue(values, 13);
this.key14 = lookupKey(keys, 14);
this.value14 = lookupValue(values, 14);
this.key15 = lookupKey(keys, 15);
this.value15 = lookupValue(values, 15);
}
@Override
String[] keys() {
return new String[] {
key0, key1, key2, key3, key4, key5, key6, key7, key8, key9, key10, key11, key12, key13, key14, key15
};
}
@Override
Object[] values() {
return new Object[] {
value0, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11, value12,
value13, value14, value15
};
}
@Override
void write(int index, String key, Object value) {
if (index < 4) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
case 3:
key3 = key;
value3 = value;
break;
default:
throw new RuntimeException("Bug in code");
}
} else if (index < 8) {
switch (index) {
case 4:
key4 = key;
value4 = value;
break;
case 5:
key5 = key;
value5 = value;
break;
case 6:
key6 = key;
value6 = value;
break;
case 7:
key7 = key;
value7 = value;
break;
default:
throw new RuntimeException("Bug in code");
}
} else if (index < 12) {
switch (index) {
case 8:
key8 = key;
value8 = value;
break;
case 9:
key9 = key;
value9 = value;
break;
case 10:
key10 = key;
value10 = value;
break;
case 11:
key11 = key;
value11 = value;
break;
default:
throw new RuntimeException("Bug in code");
}
} else {
switch (index) {
case 12:
key12 = key;
value12 = value;
break;
case 13:
key13 = key;
value13 = value;
break;
case 14:
key14 = key;
value14 = value;
break;
case 15:
key15 = key;
value15 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
}
@Override
Dictionary expand(String key, Object value) {
return new DictionaryMax(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary11.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary11(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary16(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary2.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary2 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 2;
String key0;
Object value0;
String key1;
Object value1;
// Expand constructor
public Dictionary2(Dictionary1 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
// Last key
this.key1 = key;
this.value1 = value;
}
// Contract constructor
public Dictionary2(Dictionary3 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
}
// Copy constructor
public Dictionary2(Dictionary2 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
}
// FromMap constructor
public Dictionary2(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
}
@Override
String[] keys() {
return new String[] {key0, key1};
}
@Override
Object[] values() {
return new Object[] {value0, value1};
}
@Override
void write(int index, String key, Object value) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary3(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary1.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary1(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary2(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary3.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary3 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 3;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
// Expand constructor
public Dictionary3(Dictionary2 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
// Last key
this.key2 = key;
this.value2 = value;
}
// Contract constructor
public Dictionary3(Dictionary4 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
}
// Copy constructor
public Dictionary3(Dictionary3 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
}
// FromMap constructor
public Dictionary3(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
}
@Override
String[] keys() {
return new String[] {key0, key1, key2};
}
@Override
Object[] values() {
return new Object[] {value0, value1, value2};
}
@Override
void write(int index, String key, Object value) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary4(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary2.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary2(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary3(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary4.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary4 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 4;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
String key3;
Object value3;
// Expand constructor
public Dictionary4(Dictionary3 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
// Last key
this.key3 = key;
this.value3 = value;
}
// Contract constructor
public Dictionary4(Dictionary6 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
}
// Copy constructor
public Dictionary4(Dictionary4 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
}
// FromMap constructor
public Dictionary4(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
this.key3 = lookupKey(keys, 3);
this.value3 = lookupValue(values, 3);
}
@Override
String[] keys() {
return new String[] {key0, key1, key2, key3};
}
@Override
Object[] values() {
return new Object[] {value0, value1, value2, value3};
}
@Override
void write(int index, String key, Object value) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
case 3:
key3 = key;
value3 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary6(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary3.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary3(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary4(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary6.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary6 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 6;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
String key3;
Object value3;
String key4;
Object value4;
String key5;
Object value5;
// Expand constructor
public Dictionary6(Dictionary4 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
// Last key
this.key4 = key;
this.value4 = value;
}
// Contract constructor
public Dictionary6(Dictionary8 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
}
// Copy constructor
public Dictionary6(Dictionary6 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
}
// FromMap constructor
public Dictionary6(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
this.key3 = lookupKey(keys, 3);
this.value3 = lookupValue(values, 3);
this.key4 = lookupKey(keys, 4);
this.value4 = lookupValue(values, 4);
this.key5 = lookupKey(keys, 5);
this.value5 = lookupValue(values, 5);
}
@Override
String[] keys() {
return new String[] {key0, key1, key2, key3, key4, key5};
}
@Override
Object[] values() {
return new Object[] {value0, value1, value2, value3, value4, value5};
}
@Override
void write(int index, String key, Object value) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
case 3:
key3 = key;
value3 = value;
break;
case 4:
key4 = key;
value4 = value;
break;
case 5:
key5 = key;
value5 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary8(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary4.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary4(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary6(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/Dictionary8.java
================================================
package com.lambdazen.bitsy.ads.dict;
public class Dictionary8 extends PrimitiveDictionary implements Dictionary {
public static final int CAPACITY = 8;
String key0;
Object value0;
String key1;
Object value1;
String key2;
Object value2;
String key3;
Object value3;
String key4;
Object value4;
String key5;
Object value5;
String key6;
Object value6;
String key7;
Object value7;
// Expand constructor
public Dictionary8(Dictionary6 base, String key, Object value) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
// Last key
this.key6 = key;
this.value6 = value;
}
// Contract constructor
public Dictionary8(Dictionary11 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
}
// Copy constructor
public Dictionary8(Dictionary8 base) {
this.key0 = base.key0;
this.value0 = base.value0;
this.key1 = base.key1;
this.value1 = base.value1;
this.key2 = base.key2;
this.value2 = base.value2;
this.key3 = base.key3;
this.value3 = base.value3;
this.key4 = base.key4;
this.value4 = base.value4;
this.key5 = base.key5;
this.value5 = base.value5;
this.key6 = base.key6;
this.value6 = base.value6;
this.key7 = base.key7;
this.value7 = base.value7;
}
// FromMap constructor
public Dictionary8(String[] keys, Object[] values) {
this.key0 = lookupKey(keys, 0);
this.value0 = lookupValue(values, 0);
this.key1 = lookupKey(keys, 1);
this.value1 = lookupValue(values, 1);
this.key2 = lookupKey(keys, 2);
this.value2 = lookupValue(values, 2);
this.key3 = lookupKey(keys, 3);
this.value3 = lookupValue(values, 3);
this.key4 = lookupKey(keys, 4);
this.value4 = lookupValue(values, 4);
this.key5 = lookupKey(keys, 5);
this.value5 = lookupValue(values, 5);
this.key6 = lookupKey(keys, 6);
this.value6 = lookupValue(values, 6);
this.key7 = lookupKey(keys, 7);
this.value7 = lookupValue(values, 7);
}
@Override
String[] keys() {
return new String[] {key0, key1, key2, key3, key4, key5, key6, key7};
}
@Override
Object[] values() {
return new Object[] {value0, value1, value2, value3, value4, value5, value6, value7};
}
@Override
void write(int index, String key, Object value) {
if (index < 4) {
switch (index) {
case 0:
key0 = key;
value0 = value;
break;
case 1:
key1 = key;
value1 = value;
break;
case 2:
key2 = key;
value2 = value;
break;
case 3:
key3 = key;
value3 = value;
break;
default:
throw new RuntimeException("Bug in code");
}
} else {
switch (index) {
case 4:
key4 = key;
value4 = value;
break;
case 5:
key5 = key;
value5 = value;
break;
case 6:
key6 = key;
value6 = value;
break;
case 7:
key7 = key;
value7 = value;
break;
default:
throw new IllegalArgumentException("Invalid index " + index);
}
}
}
@Override
Dictionary expand(String key, Object value) {
return new Dictionary11(this, key, value);
}
@Override
int contractThreshold() {
return Dictionary6.CAPACITY;
}
@Override
Dictionary contract() {
return new Dictionary6(this);
}
@Override
public Dictionary copyOf() {
return new Dictionary8(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/DictionaryFactory.java
================================================
package com.lambdazen.bitsy.ads.dict;
import java.util.Map;
public class DictionaryFactory {
public static Dictionary fromMap(Map properties) {
if (properties == null) {
return null;
}
int size = properties.size();
String[] keys = new String[size];
Object[] values = new Object[size];
int counter = 0;
for (Map.Entry entry : properties.entrySet()) {
keys[counter] = entry.getKey();
values[counter] = entry.getValue();
counter++;
}
// assert counter == size;
if (size == 0) {
return null;
} else if (size <= 1) {
return new Dictionary1(keys[0], values[0]);
} else if (size <= 2) {
return new Dictionary2(keys, values);
} else if (size <= 3) {
return new Dictionary3(keys, values);
} else if (size <= 4) {
return new Dictionary4(keys, values);
} else if (size <= 6) {
return new Dictionary6(keys, values);
} else if (size <= 8) {
return new Dictionary8(keys, values);
} else if (size <= 11) {
return new Dictionary11(keys, values);
} else if (size <= 16) {
return new Dictionary16(keys, values);
} else {
return new DictionaryMax(keys, values);
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/DictionaryMax.java
================================================
package com.lambdazen.bitsy.ads.dict;
import java.util.Arrays;
public class DictionaryMax extends PrimitiveDictionary implements Dictionary {
int capacity;
String[] keys;
Object[] values;
// Expand constructor
public DictionaryMax(Dictionary16 base, String key, Object value) {
this.capacity = 24;
keys = Arrays.copyOf(base.keys(), capacity);
values = Arrays.copyOf(base.values(), capacity);
keys[16] = key;
values[16] = value;
}
// Copy constructor
public DictionaryMax(DictionaryMax base) {
this.capacity = base.capacity;
keys = Arrays.copyOf(base.keys(), capacity);
values = Arrays.copyOf(base.values(), capacity);
}
// FromMap constructor
public DictionaryMax(String[] keys, Object[] values) {
this.capacity = Math.max(24, keys.length + keys.length / 2);
this.keys = Arrays.copyOf(keys, capacity);
this.values = Arrays.copyOf(values, capacity);
}
@Override
String[] keys() {
return keys;
}
@Override
Object[] values() {
return values;
}
@Override
void write(int index, String key, Object value) {
keys[index] = key;
values[index] = value;
}
@Override
Dictionary expand(String key, Object value) {
int newCapacity = capacity + (capacity / 2);
keys = Arrays.copyOf(keys, newCapacity);
values = Arrays.copyOf(values, newCapacity);
keys[capacity] = key;
values[capacity] = value;
this.capacity = newCapacity;
return this;
}
@Override
int contractThreshold() {
return capacity / 2;
}
@Override
Dictionary contract() {
if (capacity < 14) {
// Move to Dictionary16
return new Dictionary16(this);
} else {
int newCapacity = capacity * 3 / 4;
keys = Arrays.copyOf(keys, newCapacity);
values = Arrays.copyOf(values, newCapacity);
this.capacity = newCapacity;
return this;
}
}
@Override
public Dictionary copyOf() {
return new DictionaryMax(this);
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/dict/PrimitiveDictionary.java
================================================
package com.lambdazen.bitsy.ads.dict;
import com.lambdazen.bitsy.store.IStringCanonicalizer;
import java.util.Arrays;
public abstract class PrimitiveDictionary implements Dictionary {
public PrimitiveDictionary() {
// Nothing to do
}
abstract String[] keys();
abstract Object[] values();
abstract void write(int index, String key, Object value);
abstract Dictionary expand(String key, Object value);
abstract int contractThreshold();
abstract Dictionary contract();
public abstract Dictionary copyOf();
public int size() {
String[] keys = keys();
int i;
for (i = 0; i < keys.length; i++) {
if (keys[i] == null) {
break;
}
}
return i;
}
public String[] getPropertyKeys() {
String[] keys = keys();
int i;
for (i = 0; i < keys.length; i++) {
if (keys[i] == null) {
break;
}
}
return Arrays.copyOf(keys, i);
}
@Override
public Object getProperty(String key) {
String[] keys = keys();
Object[] values = values();
for (int i = 0; i < keys.length; i++) {
String curKey = keys[i];
if (curKey == null) {
// End of keys
return null;
} else if (curKey.equals(key)) {
return values[i];
}
}
return null;
}
@Override
public Dictionary setProperty(String key, Object value) {
String[] keys = keys();
Object[] values = values();
boolean overwroteValue = false;
int i;
for (i = 0; i < keys.length; i++) {
String curKey = keys[i];
if (curKey == null) {
// End of keys
break;
} else if (keys[i].equals(key)) {
values[i] = value;
write(i, keys[i], value);
overwroteValue = true;
}
}
if (overwroteValue) {
// Stick with this
return this;
} else {
if (i == keys.length) {
// Reached end, need to move up
return expand(key, value);
} else {
// Not yet at the end
write(i, key, value);
return this;
}
}
}
@Override
public void canonicalizeKeys(IStringCanonicalizer canonicalizer) {
String[] keys = keys();
Object[] values = null;
int i = 0;
for (i = 0; i < keys.length; i++) {
String origKey = keys[i];
String newKey = canonicalizer.canonicalize(origKey);
// Avoid step if already canonical
if (newKey != origKey) {
if (values == null) {
// Don't generate values unless required
values = values();
}
write(i, newKey, values[i]);
}
i++;
}
}
@Override
public Dictionary removeProperty(String key) {
String[] keys = keys();
Object[] values = values();
int overwritePos = -1;
int i;
for (i = 0; i < keys.length; i++) {
String curKey = keys[i];
if (curKey == null) {
// End of keys
break;
} else if (keys[i].equals(key)) {
overwritePos = i;
}
}
if (overwritePos == -1) {
// Couldn't find key
return this;
} else {
// Overwrite from end to here
int lastIdx = i - 1;
if (overwritePos != lastIdx) {
write(overwritePos, keys[lastIdx], values[lastIdx]);
}
write(lastIdx, null, null);
if (lastIdx <= contractThreshold()) {
// The new size is at or below the contract threshold
return contract();
} else {
return this;
}
}
}
protected String lookupKey(String[] keys, int i) {
return (i < keys.length) ? keys[i] : null;
}
protected Object lookupValue(Object[] values, int i) {
return (i < values.length) ? values[i] : null;
}
public String toString() {
StringBuilder ans = new StringBuilder("PrimitiveDictionary(size = " + size());
for (String key : getPropertyKeys()) {
ans.append(", " + key + ": " + getProperty(key));
}
ans.append(")");
return ans.toString();
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/set/ArraySet.java
================================================
package com.lambdazen.bitsy.ads.set;
import java.util.Arrays;
/**
* This class uses an array-based set implementation rather than SetMax and
* CompactMultiSetMax classes that implement a hash-based set. Neither
* implementation throws ConcurrentModificationException on reads, but expect
* writes to be serialized.
*/
public class ArraySet implements Set {
int size;
Object[] elements;
public ArraySet(Object[] elements) {
this(elements, elements.length);
}
protected ArraySet(Object[] elements, int size) {
this.size = size;
this.elements = new Object[size + size / 2];
for (int i = 0; i < size; i++) {
this.elements[i] = (T) elements[i];
}
}
@Override
public int size() {
return size;
}
@Override
public Object[] getElements() {
return Arrays.copyOf(elements, size);
}
@Override
public Object removeElement(T elem) {
// Go over elements and remove the one
for (int i = 0; i < size; i++) {
if (elem.equals(elements[i])) {
if (i < size - 1) {
elements[i] = elements[size - 1];
}
this.size--;
elements[size] = null;
break;
}
}
if (size < 16) {
return new Set24(getElements());
} else if (size < elements.length / 2) {
// Using the constructor that cuts the size -- to avoid two array creations
return new ArraySet(elements, size);
} else {
// Use the same object
return this;
}
}
@Override
public Set addElement(T elem) {
for (int i = 0; i < size; i++) {
if (elem.equals(elements[i])) {
// Nothing to do
return this;
}
}
if (size < elements.length) {
elements[size] = elem;
this.size++;
return this;
} else {
Set ans = new ArraySet(elements);
ans.addElement(elem);
return ans;
}
}
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/set/ClassifierGetter.java
================================================
package com.lambdazen.bitsy.ads.set;
public interface ClassifierGetter {
public C getClassifier(T obj);
}
================================================
FILE: src/main/java/com/lambdazen/bitsy/ads/set/CompactMultiSetMax.java
================================================
package com.lambdazen.bitsy.ads.set;
import java.util.ArrayList;
import java.util.List;
/**
* The compact multi-set takes an element and a classifier on that element. It
* supports a get that takes the classifier and returns the matches. This class
* is NOT thread-safe, but can support multiple readers as long as there is only
* one writer.
*
* This class is used for two purposes. The first is to store adjacency lists by
* label. The classifier picks up the label from the Edge. The second purpose is
* to provide SetMax with a thread-safe HashSet implementation.
*/
public class CompactMultiSetMax {
public static final int MIN_TO_RESIZE = 8;
int occupied = 0;
boolean safe;
Object[] elements;
public CompactMultiSetMax(int initSize, boolean safe) {
this.elements = new Object[initSize];
this.occupied = 0;
this.safe = safe;
}
public int getOccupiedCells() {
return this.occupied;
}
public CompactMultiSetMax add(T obj, ClassifierGetter c) {
Object classifier = c.getClassifier(obj);
addElementNoRehash(classifier.hashCode(), obj);
int len = elements.length;
if (occupied >= len - (len / 4)) { // 0.75 load factor
return rehash(len * 2, c);
} else {
return this;
}
}
protected void addElementNoRehash(int hashCode, T obj) {
int index = (hashCode & 0x7FFFFFFF) % elements.length;
if (elements[index] == null) {
occupied++;
}
if (safe) {
elements[index] = CompactSet.addSafe(elements[index], obj);
} else {
elements[index] = CompactSet.add(elements[index], obj);
}
}
private CompactMultiSetMax rehash(int newLength, ClassifierGetter c) {
CompactMultiSetMax ans = new CompactMultiSetMax(newLength, safe); // use the same safe boolean
for (Object elem : elements) {
for (Object item : CompactSet.getElements(elem)) {
Object classifier = c.getClassifier((T) item);
ans.addElementNoRehash(classifier.hashCode(), (T) item);
}
}
return ans;
}
public CompactMultiSetMax remove(T obj, ClassifierGetter c) {
Object classifier = c.getClassifier(obj);
removeElementNoHash(classifier.hashCode(), obj);
int len = elements.length;
if ((occupied > MIN_TO_RESIZE) && (occupied < len / 2)) {
return rehash(len / 2, c);
} else {
return this;
}
}
protected void removeElementNoHash(int hashCode, T obj) {
int index = (hashCode & 0x7FFFFFFF) % elements.length;
Object oldVal = elements[index];
if (oldVal == null) {
return;
} else {
Object newVal = CompactSet.remove(oldVal, obj);
elements[index] = newVal;
if (newVal == null) {
occupied--;
}
}
}
/*
* Returns a CompactSet-compatible object with the given classifier. Note that
* extra elements could be returned -- hence "super set". It is the
* responsibility of the caller to weed these out
*/
public Object[] getSuperSetWithClassifier(C key) {
if (key == null) {
return getAllElements();
} else {
int index = (key.hashCode() & 0x7FFFFFFF) % elements.length;
return CompactSet.getElements(elements[index]);
}
}
public Object[] getAllElements() {
List