├── .classpath ├── .gitignore ├── .project ├── .settings ├── org.eclipse.jdt.core.prefs ├── org.eclipse.ltk.core.refactoring.prefs └── org.eclipse.m2e.core.prefs ├── AUTHORS ├── LICENSE ├── README.md ├── config.properties ├── packaging ├── common │ ├── stacksync-server │ └── stacksync-server.1.gz └── debian │ ├── Makefile │ └── debian │ ├── changelog │ ├── compat │ ├── conffiles │ ├── control │ ├── dirs │ ├── postinst │ ├── postrm │ ├── prerm │ └── stacksync-server.init ├── pom.xml ├── script ├── adduser.sh └── install_deps.sh └── src ├── main ├── java │ └── com │ │ └── stacksync │ │ └── syncservice │ │ ├── SyncServiceDaemon.java │ │ ├── db │ │ ├── ConnectionPool.java │ │ ├── ConnectionPoolFactory.java │ │ ├── DAOError.java │ │ ├── DAOFactory.java │ │ ├── DAOUtil.java │ │ ├── DeviceDAO.java │ │ ├── ItemDAO.java │ │ ├── ItemVersionDAO.java │ │ ├── UserDAO.java │ │ ├── WorkspaceDAO.java │ │ └── postgresql │ │ │ ├── PostgresqlConnectionPool.java │ │ │ ├── PostgresqlDAO.java │ │ │ ├── PostgresqlDeviceDAO.java │ │ │ ├── PostgresqlItemDAO.java │ │ │ ├── PostgresqlItemVersionDao.java │ │ │ ├── PostgresqlUserDAO.java │ │ │ └── PostgresqlWorkspaceDAO.java │ │ ├── exceptions │ │ ├── CommitExistantVersion.java │ │ ├── CommitWrongVersion.java │ │ ├── InternalServerError.java │ │ ├── InvalidReader.java │ │ ├── NotEnoughConsumersException.java │ │ ├── dao │ │ │ ├── DAOConfigurationException.java │ │ │ ├── DAOException.java │ │ │ ├── NoGeneratedKeysDAOException.java │ │ │ ├── NoResultReturnedDAOException.java │ │ │ └── NoRowsAffectedDAOException.java │ │ └── storage │ │ │ ├── EndpointNotFoundException.java │ │ │ ├── NoStorageManagerAvailable.java │ │ │ ├── ObjectNotFoundException.java │ │ │ ├── UnauthorizedException.java │ │ │ └── UnexpectedStatusCodeException.java │ │ ├── handler │ │ ├── APIHandler.java │ │ ├── Handler.java │ │ ├── SQLAPIHandler.java │ │ ├── SQLSyncHandler.java │ │ ├── SyncHandler.java │ │ └── UnshareData.java │ │ ├── omq │ │ └── SyncServiceImp.java │ │ ├── rpc │ │ ├── Reader.java │ │ ├── XmlRpcRequestHandlerFactory.java │ │ ├── XmlRpcSyncHandler.java │ │ ├── XmlRpcSyncServer.java │ │ ├── messages │ │ │ ├── APICommitResponse.java │ │ │ ├── APICreateFolderResponse.java │ │ │ ├── APIDeleteResponse.java │ │ │ ├── APIGetFolderMembersResponse.java │ │ │ ├── APIGetMetadata.java │ │ │ ├── APIGetVersions.java │ │ │ ├── APIGetWorkspaceInfoResponse.java │ │ │ ├── APIResponse.java │ │ │ ├── APIRestoreMetadata.java │ │ │ ├── APIShareFolderResponse.java │ │ │ ├── APIUnshareFolderResponse.java │ │ │ └── APIUserMetadata.java │ │ └── parser │ │ │ ├── IParser.java │ │ │ └── JSONParser.java │ │ ├── storage │ │ ├── StorageFactory.java │ │ ├── StorageManager.java │ │ ├── SwiftManager.java │ │ ├── SwiftManagerHTTPS.java │ │ ├── SwiftResponse.java │ │ └── swift │ │ │ ├── AccessObject.java │ │ │ ├── EndpointObject.java │ │ │ ├── LoginResponseObject.java │ │ │ ├── ServiceObject.java │ │ │ └── TokenObject.java │ │ └── util │ │ ├── CleanObjects.java │ │ ├── Config.java │ │ └── Constants.java └── resources │ ├── example.properties │ ├── log4j.xml │ ├── setup_db.sql │ └── version.properties └── test └── java └── com └── stacksync └── syncservice └── test ├── benchmark ├── Constants.java ├── DBBenchmark.java ├── MetadataGenerator.java ├── db │ └── DatabaseHelper.java ├── normal │ ├── CommonFunctions.java │ ├── RandomString.java │ ├── TestCommit.java │ ├── TestGetChanges.java │ └── TestGetWorkspaces.java └── omq │ ├── RabbitConfig.java │ ├── TestCommit.java │ ├── TestGetChanges.java │ └── TestGetWorkspaces.java ├── dao └── PostgresqlDAOTest.java ├── handler ├── AdvancedHandlerTest.java ├── BasicHandlerTest.java ├── CreateFileTest.java ├── GetMetadataTest.java ├── GetWorkspaceInfoTest.java ├── SendShareNotificationTest.java ├── ShareFolderTest.java ├── SharingTest.java ├── UpdateDataTest.java ├── UpdateDeviceTest.java └── UpdateMetadataTest.java ├── main └── ServerTest.java ├── reader └── JSONParserTest.java └── xmlrpc ├── ApiCreateFolder.java ├── ApiDeleteMetadataFile.java ├── ApiGetMetadata.java ├── ApiGetVersions.java ├── ApiPutMetadataFile.java ├── ApiPutMetadataFolder.java ├── ApiRestoreMetadata.java └── Constants.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Package Files # 4 | *.jar 5 | *.war 6 | *.ear 7 | /target/ 8 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | sync-service 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore 3 | org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull 4 | org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault 5 | org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable 6 | org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled 7 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 8 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 9 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 10 | org.eclipse.jdt.core.compiler.compliance=1.6 11 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 12 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 13 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 14 | org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning 15 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 16 | org.eclipse.jdt.core.compiler.problem.autoboxing=ignore 17 | org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning 18 | org.eclipse.jdt.core.compiler.problem.deadCode=warning 19 | org.eclipse.jdt.core.compiler.problem.deprecation=warning 20 | org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled 21 | org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled 22 | org.eclipse.jdt.core.compiler.problem.discouragedReference=warning 23 | org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore 24 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 25 | org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore 26 | org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore 27 | org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled 28 | org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore 29 | org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning 30 | org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning 31 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 32 | org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning 33 | org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled 34 | org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning 35 | org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning 36 | org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore 37 | org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore 38 | org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning 39 | org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore 40 | org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore 41 | org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled 42 | org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore 43 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore 44 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled 45 | org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning 46 | org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore 47 | org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning 48 | org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning 49 | org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore 50 | org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error 51 | org.eclipse.jdt.core.compiler.problem.nullReference=warning 52 | org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error 53 | org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning 54 | org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning 55 | org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore 56 | org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore 57 | org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore 58 | org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore 59 | org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning 60 | org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning 61 | org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore 62 | org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore 63 | org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore 64 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore 65 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore 66 | org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled 67 | org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning 68 | org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled 69 | org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled 70 | org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore 71 | org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning 72 | org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled 73 | org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning 74 | org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning 75 | org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore 76 | org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning 77 | org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore 78 | org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore 79 | org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore 80 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore 81 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled 82 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled 83 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled 84 | org.eclipse.jdt.core.compiler.problem.unusedImport=warning 85 | org.eclipse.jdt.core.compiler.problem.unusedLabel=warning 86 | org.eclipse.jdt.core.compiler.problem.unusedLocal=warning 87 | org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore 88 | org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore 89 | org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled 90 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled 91 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled 92 | org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning 93 | org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning 94 | org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning 95 | org.eclipse.jdt.core.compiler.source=1.6 96 | -------------------------------------------------------------------------------- /.settings/org.eclipse.ltk.core.refactoring.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false 3 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | StackSync SyncService is written by: 2 | Cristian Cotes {cristian.cotes [at] urv [dot] cat} 3 | Guillermo Guerrero {guillermo.guerrero [at] urv [dot] cat} 4 | Adrian Moreno {adrian [at] morenomartinez [dot] com} 5 | 6 | 7 | Authors are ordered alphabetically by their surname. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DISCONTINUED 2 | 3 | StackSync development and maintenance has been discontinued. Thank you to all collaborators that participated in this amazing project. 4 | 5 | 6 | StackSync Synchronization service 7 | ================================= 8 | 9 | 10 | **Table of Contents** 11 | 12 | - [Introduction](#introduction) 13 | - [Architecture](#architecture) 14 | - [Synchronization service](#synchronization-service) 15 | - [Requirements](#requirements) 16 | - [Setup](#setup) 17 | - [Database initialization](#database-initialization) 18 | - [Create admin user](#create-admin-user) 19 | - [Create new users](#create-new-users) 20 | - [Compilation](#compilation) 21 | - [Installation](#installation) 22 | - [Issue Tracking](#issue-tracking) 23 | - [Licensing](#licensing) 24 | - [Contact](#contact) 25 | 26 | 27 | # Introduction 28 | 29 | StackSync () is a scalable open source Personal Cloud 30 | that implements the basic components to create a synchronization tool. 31 | 32 | 33 | # Architecture 34 | 35 | In general terms, StackSync can be divided into three main blocks: clients 36 | (desktop and mobile), synchronization service (SyncService) and storage 37 | service (Swift, Amazon S3, FTP...). An overview of the architecture 38 | with the main components and their interaction is shown in the following image. 39 | 40 |

41 | 42 |

43 | 44 | The StackSync client and the SyncService interact through the communication 45 | middleware called ObjectMQ. The sync service interacts with the metadata 46 | database. The StackSync client directly interacts with the storage back-end 47 | to upload and download files. 48 | 49 | As storage back-end we are using OpenStack Swift, an open source cloud storage 50 | software where you can store and retrieve lots of data in virtual containers. 51 | It's based on the Cloud Files offering from Rackspace. But it is also possible 52 | to use other storage back-ends, such as a FTP server or S3. 53 | 54 | 55 | # Synchronization service 56 | 57 | The SyncService is in charge of managing the metadata in order to achieve 58 | data synchronization. Desktop clients communicate with the SyncService for two main 59 | reasons: to obtain the changes occurred when they were offline; and to commit new versions 60 | of a files. 61 | 62 | When a client connects to the system, the first thing it does is asking the SyncService 63 | for changes that were made during the offline time period. This is very common situation 64 | for users working with two different computers, e.g., home and work. Assuming the home 65 | computer is off, if the user modifies some files while at work, the home computer will not 66 | realize about these changes until the user turns on the computer. At this time, the client will 67 | ask the SyncService and update to apply the changes made at work. 68 | 69 | When the server receives a commit operation of a file, it must first check that the meta- 70 | data received is consistent. If the metadata is correct, it proceeds to save it to a database. 71 | Afterwards, a notification is sent to all devices owned by the user reporting the file update. 72 | This provides StackSync with real-time in all devices as they receive notifications of updates 73 | and are always synchronized. However, if the metadata is incorrect, an notification is sent 74 | to the client to fix the error. 75 | 76 | 77 | # Requirements 78 | 79 | * Java 1.6 or newer 80 | * Maven 2 81 | * PostgreSQL 9 82 | * RabbitMQ 3.2.X (Version 3.3.X is not compatible) 83 | 84 | # Setup 85 | 86 | ## Database initialization 87 | 88 | In order to initialize the database we need to create the database and the user and execute the script “setup_db.sql” located in "src/main/resources". 89 | 90 | First, enter in a Postgres command line mode: 91 | 92 | $ sudo -u postgres psql 93 | 94 | Execute the commands below to create a user and the database. The database must be called stacksync: 95 | 96 | postgres=# create database stacksync; 97 | postgres=# create user stacksync_user with password 'mysecretpwd'; 98 | postgres=# grant all privileges on database db_name to db_user; 99 | postgres=# \connect db_name 100 | postgres=# CREATE EXTENSION "uuid-ossp"; 101 | postgres=# \q 102 | 103 | Enter to the database with the user role created. Note that the first parameter is the host, the second is the database name and the last one is the username: 104 | 105 | $ psql -h localhost db_name db_user 106 | 107 | Now run execute the script. 108 | 109 | postgres=# \i ./setup_db.sql 110 | postgres=# \q 111 | 112 | ## Create admin user 113 | 114 | In order to manage StackSync users in Swift (create containers, set ACLs...) it is necessary to create an admin user in Swift. 115 | 116 | First of all, create a tenant for StackSync: 117 | 118 | $ keystone tenant-create stacksync 119 | 120 | After that, create the admin user under this tenant: 121 | 122 | $ keystone user-create --name stacksync_admin --tenant stacksync --pass "secr3te" 123 | 124 | Finally, assign the admin role to the stacksync_admin user: 125 | 126 | $ keystone user-role-add --user stacksync_admin --role admin --tenant stacksync 127 | 128 | ## Create new users 129 | 130 | Go to the web manager project: 131 | https://github.com/stacksync/manager 132 | 133 | 134 | # Compilation 135 | 136 | We just need to assemble the project into a JAR using Maven: 137 | 138 | $ mvn assembly:assembly 139 | 140 | This will generate a "target" folder containing a JAR file called "syncservice-X.X-jar-with-dependencies.jar" 141 | 142 | > **NOTE**: if you get an error (BUILD FAILURE), cleaning your local Maven repository may fix the problem. 143 | 144 | $ rm -rf ~/.m2/repository/* 145 | 146 | # Create deb package 147 | 148 | Under the folder [packaging/debian](packaging/debian) there is the Makefile to create the deb file. 149 | 150 | $ cd packaging/debian 151 | $ make compile 152 | $ make package 153 | 154 | # Installation 155 | First, install the deb package: 156 | 157 | $ sudo dpkg -i stacksync-server_X.X.X_all.deb 158 | 159 | The StackSync Server has a dependency with the JSVC library, if you experience any problem while installing run the following command: 160 | 161 | $ sudo apt-get -f install 162 | 163 | Once the server is installed, you must modify the configuration file to connect with the database, the messaging middleware, and OpenStack Swift. 164 | 165 | You need to specify a Keystone user capable of creating users and set up ACL on containers on the specific container configured in the file. 166 | 167 | /etc/stacksync-server/stacksync-server.conf 168 | 169 | The init script assumes that you have a "JAVA\_HOME" environment variable set up, if not, it will execute the java located in “/usr/lib/jvm/default-java”. You can change the Java VM by setting up the “JAVA\_HOME” environment or by modifying the script in: 170 | 171 | /etc/init.d/stacksync-server 172 | 173 | Once configured, just run the server. 174 | 175 | $ sudo service stacksync-server start 176 | 177 | If something went wrong, you can check the standard and error log files located in: 178 | 179 | /var/log/stacksync-server/ 180 | 181 | # Issue Tracking 182 | We use the GitHub issue tracking. 183 | 184 | # Licensing 185 | StackSync is licensed under the Apache 2.0. Check [LICENSE](LICENSE) for the latest 186 | licensing information. 187 | 188 | # Contact 189 | Visit www.stacksync.com for contact information. 190 | -------------------------------------------------------------------------------- /config.properties: -------------------------------------------------------------------------------- 1 | # StackSync - SyncService configuration 2 | # 3 | # Type of database used as metadata backend. 4 | # For the moment, only 'postgresql' is available. 5 | datasource=postgresql 6 | # 7 | # 8 | # PostgreSQL configuration 9 | # ======================== 10 | # 11 | # Host 12 | postgresql.host=localhost 13 | # 14 | # Port 15 | postgresql.port=5432 16 | # 17 | # Database 18 | postgresql.database=stacksync 19 | # 20 | # User 21 | postgresql.user=stacksync_user 22 | # 23 | # Password 24 | postgresql.password=stacksync 25 | # 26 | # 27 | # 28 | # ObjectMQ configuration 29 | # ====================== 30 | # ObjectMQ is the middleware that abstracts the communication between 31 | # the SyncService and the clients. This configuration corresponds with 32 | # the message broker service (AMQP compliant) in charge of handling this 33 | # communication. 34 | # 35 | # Host 36 | omq.host=10.30.233.214 37 | # 38 | # Port 39 | omq.port=5672 40 | # 41 | # User 42 | omq.username=guest 43 | # 44 | # Password 45 | omq.pass=guest 46 | # 47 | # Number of threads 48 | omq.num_threads=4 49 | # 50 | # Exchange queue. 51 | # Must be the same as the one the clients send their requests. 52 | omq.rpc_exchange=rpc_global_exchange 53 | # 54 | # 55 | # 56 | # OpenStack Swift configuration 57 | # ============================= 58 | # 59 | # Keystone host 60 | swift.host=10.30.233.214 61 | # 62 | # Keystone host 63 | swift.keystone_host=10.30.233.214 64 | # 65 | # Keystone port 66 | swift.keystone_port=5000 67 | # 68 | # Keystone admin port 69 | swift.keystone_admin_port=35357 70 | # 71 | # Keystone protocol 72 | swift.keystone_protocol=http 73 | # 74 | # Tenant 75 | swift.tenant=stacksync 76 | # 77 | # User 78 | swift.user=stacksync_admin 79 | # 80 | # Password 81 | swift.password=secrete 82 | # 83 | -------------------------------------------------------------------------------- /packaging/common/stacksync-server: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | 3 | /etc/init.d/stacksync-server start 4 | -------------------------------------------------------------------------------- /packaging/common/stacksync-server.1.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stacksync/sync-service/b9abe53d954fc12fffb101eabbeb9b18acd9951a/packaging/common/stacksync-server.1.gz -------------------------------------------------------------------------------- /packaging/debian/Makefile: -------------------------------------------------------------------------------- 1 | TARGET_DIR=../../target 2 | JAR_FILE=$(notdir $(wildcard $(TARGET_DIR)/stacksync-server-[0-9.]*-jar-with-dependencies.jar)) 3 | 4 | #PACKAGE_NAME=$(shell echo $(JAR_FILE) | sed -e 's/\(-jar-with-dependencies.jar\)//g') 5 | PACKAGE_NAME=stacksync-server 6 | VERSION=$(shell echo $(JAR_FILE) | sed -e 's:stacksync-server-\(.*\)-jar-with-dependencies.jar:\1:g') 7 | CONFIG_DIR=../.. 8 | COMMONS_DIR=../common 9 | 10 | all: 11 | @echo 'Please choose a target from the Makefile.' 12 | 13 | .PHONY: clean 14 | 15 | compile: 16 | @cd ../..; mvn clean dependency:copy-dependencies assembly:assembly 17 | 18 | package: clean 19 | # Add changes to changelog 20 | #dch -v $(VERSION) 21 | # Compile source 22 | #cd ../../; mvn clean assembly:assembly 23 | # Create package folder and folder structure 24 | @mkdir -p $(PACKAGE_NAME)/usr/lib/stacksync-server/lib 25 | @mkdir -p $(PACKAGE_NAME)/usr/bin 26 | @mkdir -p $(PACKAGE_NAME)/usr/share/man/man1 27 | @mkdir -p $(PACKAGE_NAME)/var/log/stacksync-server 28 | @mkdir -p $(PACKAGE_NAME)/etc/stacksync-server 29 | @mkdir -p $(PACKAGE_NAME)/etc/init.d 30 | # Copy DEBIAN folder 31 | @cp -r debian $(PACKAGE_NAME)/DEBIAN 32 | # Copy the JAR file 33 | @cp $(TARGET_DIR)/$(JAR_FILE) $(PACKAGE_NAME)/usr/lib/stacksync-server/stacksync-server.jar 34 | # Copy bin script 35 | @cp $(COMMONS_DIR)/stacksync-server $(PACKAGE_NAME)/usr/bin/ 36 | # Copy commons-daemon lib 37 | @cp $(TARGET_DIR)/commons-daemon-1.0.15.jar $(PACKAGE_NAME)/usr/lib/stacksync-server/lib/ 38 | # Copy man page 39 | @cp $(COMMONS_DIR)/stacksync-server.1.gz $(PACKAGE_NAME)/usr/share/man/man1/ 40 | # Copy configuration file 41 | @cp $(CONFIG_DIR)/config.properties $(PACKAGE_NAME)/etc/stacksync-server/stacksync-server.conf 42 | # Move init script 43 | @mv $(PACKAGE_NAME)/DEBIAN/stacksync-server.init $(PACKAGE_NAME)/etc/init.d/stacksync-server 44 | # FIXME: Calculate package size 45 | INSTALLED_SIZE=$(du -sx --exclude DEBIAN $(PACKAGE_NAME) | cut -f1) 46 | # TODO: Update package size 47 | sed -i 's/INSTALLED_SIZE/$(INSTALLED_SIZE)/g' $(PACKAGE_NAME)/DEBIAN/control 48 | # Update version 49 | @sed -i 's/VERSION/$(VERSION)/g' $(PACKAGE_NAME)/DEBIAN/control 50 | # Generate md5sum file 51 | @cd $(PACKAGE_NAME); find . -type f ! -regex '.*.hg.*' ! -regex '.*?debian-binary.*' ! -regex '.*?DEBIAN.*' -printf '%P ' | xargs md5sum > DEBIAN/md5sums 52 | # Create debian package 53 | @dpkg --build $(PACKAGE_NAME) stacksync-server_$(VERSION)_all.deb 54 | 55 | 56 | clean: 57 | rm -rf $(PACKAGE_NAME) 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /packaging/debian/debian/changelog: -------------------------------------------------------------------------------- 1 | stacksync-server (0.4.4) unstable; urgency=low 2 | 3 | * Initial Release 4 | 5 | -- Adrian Moreno Tue, 03 Dec 2013 16:26:02 +0100 6 | -------------------------------------------------------------------------------- /packaging/debian/debian/compat: -------------------------------------------------------------------------------- 1 | 7 2 | -------------------------------------------------------------------------------- /packaging/debian/debian/conffiles: -------------------------------------------------------------------------------- 1 | /etc/stacksync-server/stacksync-server.conf 2 | /etc/init.d/stacksync-server 3 | -------------------------------------------------------------------------------- /packaging/debian/debian/control: -------------------------------------------------------------------------------- 1 | Package: stacksync-server 2 | Version: VERSION 3 | Section: net 4 | Priority: extra 5 | Installed-Size: 4156 6 | Architecture: all 7 | Depends: jsvc 8 | Homepage: http://www.stacksync.org/ 9 | Maintainer: Adrian Moreno 10 | Description: StackSync is an open-source scalable Personal Cloud 11 | StackSync can adapt to the necessities of organizations and 12 | puts a special emphasis on security by encrypting data 13 | on the client side before it is sent to the server. 14 | . 15 | The StackSync Server manages metadata to guarantee a 16 | correct synchronization among all user devices. 17 | -------------------------------------------------------------------------------- /packaging/debian/debian/dirs: -------------------------------------------------------------------------------- 1 | usr/lib/stacksync-server/lib 2 | usr/bin 3 | usr/share/man/man1 4 | var/log/stacksync-server 5 | etc/stacksync-server 6 | -------------------------------------------------------------------------------- /packaging/debian/debian/postinst: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # postinst script for stacksync-server 3 | 4 | # create stacksync group 5 | if ! getent group stacksync >/dev/null; then 6 | addgroup --system stacksync 7 | fi 8 | 9 | # create stacksync user 10 | if ! getent passwd stacksync >/dev/null; then 11 | adduser --system --ingroup stacksync --home /usr/lib/stacksync-server \ 12 | --no-create-home --gecos "StackSync Server" \ 13 | --disabled-login stacksync 14 | fi 15 | 16 | 17 | touch /var/log/stacksync-server/stacksync-server.out 18 | touch /var/log/stacksync-server/stacksync-server.err 19 | chown -R stacksync:stacksync /usr/lib/stacksync-server 20 | chown -R stacksync:stacksync /var/log/stacksync-server 21 | chmod +r /var/log/stacksync-server -R 22 | 23 | 24 | if [ -x "/etc/init.d/stacksync-server" ]; then 25 | if [ ! -e "/etc/stacksync-server/stacksync-server.conf" ]; then 26 | update-rc.d stacksync-server defaults >/dev/null 27 | fi 28 | #invoke-rc.d stacksync-server start || exit $? 29 | fi 30 | -------------------------------------------------------------------------------- /packaging/debian/debian/postrm: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # postrm script for stacksync-server 3 | 4 | # Automatically added by dh_installinit 5 | #if [ "$1" = "purge" ] ; then 6 | update-rc.d stacksync-server remove >/dev/null 7 | #fi 8 | # End automatically added section 9 | 10 | if [ -d "/var/log/stacksync-server" ]; then 11 | rm -rf /var/log/stacksync-server 12 | fi 13 | 14 | if [ -x "/etc/init.d/stacksync-server" ]; then 15 | rm /etc/init.d/stacksync-server 16 | fi 17 | -------------------------------------------------------------------------------- /packaging/debian/debian/prerm: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # postinst script for stacksync-server 3 | 4 | # Automatically added by dh_installinit 5 | if [ -x "/etc/init.d/stacksync-server" ]; then 6 | invoke-rc.d stacksync-server stop || exit $? 7 | fi 8 | # End automatically added section 9 | -------------------------------------------------------------------------------- /packaging/debian/debian/stacksync-server.init: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | # /etc/init.d/stacksync-server 3 | 4 | 5 | if [ `id -u` != `id -u stacksync` -a `id -u` != 0 ] ; then 6 | echo 7 | echo "Only root or stacksync can run stacksync-server" 8 | echo 9 | exit 1 10 | fi 11 | 12 | # If JAVA_HOME environment variable is not set, get the default java VM 13 | if [ -z "$JAVA_HOME" ]; then 14 | JAVA_HOME=/usr/lib/jvm/default-java 15 | fi; 16 | 17 | NAME="stacksync-server" 18 | DESC="StackSync Server" 19 | 20 | # The path to Jsvc 21 | EXEC="/usr/bin/jsvc" 22 | 23 | # The path to the folder containing StackSyncServer.jar 24 | FILE_PATH="/usr/lib/$NAME" 25 | 26 | # Path to configuration folder 27 | CONFIG_PATH="/etc/$NAME" 28 | 29 | # Path to the log folder 30 | LOG_PATH="/var/log/$NAME" 31 | 32 | # Path to std output log 33 | LOG_STD_PATH="$LOG_PATH/stacksync-server.out" 34 | 35 | # Path to error output log 36 | LOG_ERR_PATH="$LOG_PATH/stacksync-server.err" 37 | 38 | # Our classpath including our jar file and the Apache Commons Daemon library 39 | CLASS_PATH="$FILE_PATH/stacksync-server.jar:$FILE_PATH/lib/commons-daemon-1.0.15.jar" 40 | 41 | # The fully qualified name of the class to execute 42 | CLASS="com.stacksync.syncservice.SyncServiceDaemon" 43 | 44 | # Any command line arguments to be passed to the our Java Daemon implementations init() method 45 | ARGS="$CONFIG_PATH/stacksync-server.conf" 46 | 47 | #The user to run the daemon as 48 | USER="stacksync" 49 | 50 | # The file that will contain our process identification number (pid) for other scripts/programs that need to access it. 51 | PID="/var/run/$NAME.pid" 52 | 53 | jsvc_exec() 54 | { 55 | cd $FILE_PATH 56 | $EXEC -outfile $LOG_STD_PATH -errfile $LOG_ERR_PATH -home $JAVA_HOME -cp $CLASS_PATH -user $USER -pidfile $PID -wait 10 $1 $CLASS $ARGS 57 | } 58 | 59 | case "$1" in 60 | start) 61 | echo "Starting $DESC..." 62 | 63 | # Start the service 64 | jsvc_exec 65 | 66 | if [ $? != "0" ]; then 67 | echo "$DESC could not start." 68 | exit 1 69 | fi 70 | 71 | echo "$DESC has started." 72 | ;; 73 | stop) 74 | if [ -f "$PID" ]; then 75 | echo "Stopping $DESC..." 76 | 77 | # Stop the service 78 | jsvc_exec "-stop" 79 | 80 | echo "$DESC has stopped." 81 | else 82 | echo "$DESC not running, no action taken" 83 | fi 84 | ;; 85 | restart) 86 | if [ -f "$PID" ]; then 87 | echo "Restarting the $DESC..." 88 | 89 | # Stop the service 90 | jsvc_exec "-stop" 91 | 92 | # Start the service 93 | jsvc_exec 94 | 95 | echo "The $DESC has restarted." 96 | else 97 | echo "Daemon not running, no action taken" 98 | fi 99 | ;; 100 | status) 101 | if [ -f "$PID" ]; then 102 | echo "$DESC is running." 103 | else 104 | echo "$DESC is NOT running." 105 | fi 106 | ;; 107 | *) 108 | echo "Usage: /etc/init.d/$NAME {start|stop|restart|status}" >&2 109 | exit 3 110 | ;; 111 | esac 112 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | StackSync Server 5 | com.stacksync 6 | stacksync-server 7 | 0.6.13 8 | 9 | 10 | Sonatype repository 11 | Sonatype's Maven repository 12 | http://oss.sonatype.org/content/groups/public 13 | 14 | 15 | Sonatype RSO 16 | Sonatype's Forge repository 17 | https://repository.sonatype.org/content/groups/forge 18 | 19 | 20 | ast-server2 21 | ast-server2-releases 22 | http://ast2-deim.urv.cat/artifactory/ast-internal-repository 23 | 24 | 25 | 26 | 27 | commons-daemon 28 | commons-daemon 29 | 1.0.15 30 | 31 | 32 | com.stacksync 33 | stacksync-commons 34 | 1.4.4 35 | 36 | 37 | objectmq 38 | objectmq 39 | 0.5.7 40 | 41 | 42 | junit 43 | junit 44 | 4.11 45 | 46 | 47 | com.rabbitmq 48 | amqp-client 49 | 3.0.1 50 | 51 | 52 | log4j 53 | log4j 54 | 1.2.16 55 | 56 | 57 | log4j 58 | apache-log4j-extras 59 | 1.1 60 | 61 | 62 | org.apache.xmlrpc 63 | xmlrpc-client 64 | 3.1.2 65 | 66 | 67 | org.apache.xmlrpc 68 | xmlrpc-common 69 | 3.1.2 70 | 71 | 72 | org.apache.xmlrpc 73 | xmlrpc-server 74 | 3.1.2 75 | 76 | 77 | com.google.code.gson 78 | gson 79 | 2.2.4 80 | 81 | 82 | commons-cli 83 | commons-cli 84 | 1.1 85 | 86 | 87 | commons-io 88 | commons-io 89 | 2.2 90 | 91 | 92 | postgresql 93 | postgresql 94 | 9.1-901.jdbc4 95 | 96 | 97 | org.apache.httpcomponents 98 | httpclient 99 | 4.1.2 100 | 101 | 102 | joda-time 103 | joda-time 104 | 2.3 105 | 106 | 107 | 108 | 109 | 110 | src/main/resources 111 | true 112 | 113 | log4j.xml 114 | example.properties 115 | version.properties 116 | 117 | 118 | 119 | 120 | 121 | net.sf.debian-maven 122 | debian-maven-plugin 123 | 1.0.6 124 | 125 | 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-compiler-plugin 130 | 3.1 131 | 132 | 1.6 133 | 1.6 134 | 135 | 136 | 137 | org.apache.maven.plugins 138 | maven-assembly-plugin 139 | 140 | 141 | package 142 | 143 | attached 144 | 145 | 146 | 147 | 148 | 149 | jar-with-dependencies 150 | 151 | 152 | 153 | true 154 | lib/ 155 | com.stacksync.syncservice.SyncServiceDaemon 156 | 157 | 158 | 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-dependency-plugin 163 | 164 | 165 | ${project.build.directory} 166 | 167 | 168 | 169 | 170 | org.apache.maven.plugins 171 | maven-surefire-plugin 172 | 2.14.1 173 | 174 | true 175 | 176 | 177 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /script/adduser.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# != 3 ]; then 4 | echo "USAGE ERROR:" 5 | echo -e "\tsudo $0 " 6 | exit 1 7 | fi 8 | 9 | # Keystone info 10 | IP=IP_HERE 11 | export OS_USERNAME=SWIFT_ADMIN_USER 12 | export OS_PASSWORD=SWIFT_ADMIN_USER_PASS 13 | export OS_TENANT_NAME=SWIFT_ADMIN_TENANT 14 | export OS_AUTH_URL=http://$IP:35357/v2.0 15 | 16 | # StackSync admin user info 17 | STACKSYNC_TENANT=STACKSYNC_TENANT_HERE 18 | STACKSYNC_ADMIN_USER=STACKSYNC_ADMIN_USER_HERE 19 | STACKSYNC_ADMIN_USER_PASS=STACKSYNC_ADMIN_USER_PASS_HERE 20 | 21 | # StackSync database info (postgresql) 22 | STACKSYNC_DB_HOST=localhost 23 | STACKSYNC_DB=STACKSYNC_DB_HERE 24 | STACKSYNC_USER=STACKSYNC_USER_HERE 25 | export PGPASSWORD=STACKSYNC_DB_PASS_HERE 26 | 27 | #Create stacksync user 28 | keystone user-create --name $1 --tenant $STACKSYNC_TENANT --pass $2 29 | 30 | # Login as the StackSync admin and get the token and the storage url 31 | output=$(curl -s -d '{"auth": {"passwordCredentials": {"username": "'$STACKSYNC_ADMIN_USER'", "password": "'$STACKSYNC_ADMIN_USER_PASS'"}, "tenantName":"'$STACKSYNC_TENANT'"}}' -H 'Content-type: application/json' http://$IP:5000/v2.0/tokens) 32 | 33 | ADMINTOKEN=`echo $output | ruby -e "require 'rubygems'; require 'json'; puts JSON[STDIN.read]['access']['token']['id'];"` 34 | STORAGEURL=`echo $output | ruby -e "require 'rubygems'; require 'json'; arrayJson = JSON[STDIN.read]['access']['serviceCatalog']; 35 | arrayJson.each do |object| 36 | if object['name'] == \"swift\" 37 | puts object['endpoints'][0]['publicURL']; 38 | end 39 | end"` 40 | 41 | curl -k -i -X PUT -H "X-Auth-Token: $ADMINTOKEN" -H "X-Container-Read: $STACKSYNC_TENANT:$1" -H "X-Container-Write: $STACKSYNC_TENANT:$1" $STORAGEURL/$1 42 | 43 | # Create DB content 44 | psql -h $STACKSYNC_DB_HOST $STACKSYNC_DB $STACKSYNC_USER -c "INSERT INTO user1 (name, swift_user, swift_account, email, quota_limit, quota_used) VALUES ('$1', '$1', '${STORAGEURL##*/}', '$3', 0, 0);" 45 | 46 | psql -h $STACKSYNC_DB_HOST $STACKSYNC_DB $STACKSYNC_USER -c "INSERT INTO workspace (latest_revision, owner_id, is_shared, swift_container, swift_url) VALUES (0, (SELECT id FROM user1 WHERE name='$1'), false, '$1', '$STORAGEURL');" 47 | 48 | psql -h $STACKSYNC_DB_HOST $STACKSYNC_DB $STACKSYNC_USER -c "INSERT INTO workspace_user(workspace_id, user_id, workspace_name, parent_item_id) VALUES ((SELECT id FROM workspace WHERE swift_container='$1'), (SELECT id FROM user1 WHERE name='$1'), 'default', NULL);" 49 | -------------------------------------------------------------------------------- /script/install_deps.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | if [[ $UID -ne 0 ]]; then 3 | echo "$0 must be run as root" 4 | exit 1 5 | fi 6 | 7 | ### INSTALL DEPENDENCIES 8 | apt-get -y install ruby python-keystoneclient curl 9 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/SyncServiceDaemon.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.sql.Connection; 7 | import java.sql.SQLException; 8 | import java.util.Properties; 9 | 10 | import omq.common.broker.Broker; 11 | 12 | import org.apache.commons.daemon.Daemon; 13 | import org.apache.commons.daemon.DaemonContext; 14 | import org.apache.commons.daemon.DaemonInitException; 15 | import org.apache.log4j.Logger; 16 | 17 | import com.stacksync.commons.omq.ISyncService; 18 | import com.stacksync.syncservice.db.ConnectionPool; 19 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 20 | import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException; 21 | import com.stacksync.syncservice.omq.SyncServiceImp; 22 | import com.stacksync.syncservice.rpc.XmlRpcSyncHandler; 23 | import com.stacksync.syncservice.rpc.XmlRpcSyncServer; 24 | import com.stacksync.syncservice.storage.StorageFactory; 25 | import com.stacksync.syncservice.storage.StorageManager; 26 | import com.stacksync.syncservice.storage.StorageManager.StorageType; 27 | import com.stacksync.syncservice.util.Config; 28 | import com.stacksync.syncservice.util.Constants; 29 | 30 | public class SyncServiceDaemon implements Daemon { 31 | 32 | private static final Logger logger = Logger 33 | .getLogger(SyncServiceDaemon.class.getName()); 34 | private static ConnectionPool pool = null; 35 | private static XmlRpcSyncServer xmlRpcServer = null; 36 | private static Broker broker = null; 37 | private static SyncServiceImp syncService = null; 38 | 39 | @Override 40 | public void init(DaemonContext dc) throws DaemonInitException, Exception { 41 | 42 | logger.info(String.format("Initializing StackSync Server v%s...", 43 | SyncServiceDaemon.getVersion())); 44 | 45 | logger.info(String.format("Java VM: %s", System.getProperty("java.vm.name"))); 46 | logger.info(String.format("Java VM version: %s", System.getProperty("java.vm.version"))); 47 | logger.info(String.format("Java Home: %s", System.getProperty("java.home"))); 48 | logger.info(String.format("Java version: %s", System.getProperty("java.version"))); 49 | 50 | try { 51 | String[] argv = dc.getArguments(); 52 | 53 | if (argv.length == 0) { 54 | logger.error("No config file passed to StackSync Server."); 55 | System.exit(1); 56 | } 57 | 58 | String configPath = argv[0]; 59 | 60 | File file = new File(configPath); 61 | if (!file.exists()) { 62 | logger.error("'" + configPath + "' file not found"); 63 | System.exit(2); 64 | } 65 | 66 | Config.loadProperties(configPath); 67 | 68 | } catch (IOException e) { 69 | logger.error("Could not load properties file.", e); 70 | System.exit(7); 71 | } 72 | 73 | try { 74 | 75 | String datasource = Config.getDatasource(); 76 | pool = ConnectionPoolFactory.getConnectionPool(datasource); 77 | 78 | // it will try to connect to the DB, throws exception if not 79 | // possible. 80 | Connection conn = pool.getConnection(); 81 | conn.close(); 82 | 83 | logger.info("Connection to database succeded"); 84 | } catch (DAOConfigurationException e) { 85 | logger.error("Connection to database failed.", e); 86 | System.exit(3); 87 | } catch (SQLException e) { 88 | logger.error("Connection to database failed.", e); 89 | System.exit(4); 90 | } 91 | 92 | logger.info("Connecting to OpenStack Swift..."); 93 | 94 | try { 95 | StorageType type; 96 | if (Config.getSwiftKeystoneProtocol().equals("http")) { 97 | type = StorageType.SWIFT; 98 | } else { 99 | type = StorageType.SWIFT_SSL; 100 | } 101 | StorageManager storageManager = StorageFactory.getStorageManager(type); 102 | storageManager.login(); 103 | logger.info("Connected to OpenStack Swift successfully"); 104 | } catch (Exception e) { 105 | logger.fatal("Could not connect to Swift.", e); 106 | System.exit(7); 107 | } 108 | 109 | 110 | logger.info("Initializing the messaging middleware..."); 111 | try { 112 | broker = new Broker(Config.getProperties()); 113 | syncService = new SyncServiceImp(broker, pool); 114 | logger.info("Messaging middleware initialization succeeded"); 115 | } catch (Exception e) { 116 | logger.error("Could not initialize ObjectMQ.", e); 117 | System.exit(5); 118 | } 119 | } 120 | 121 | @Override 122 | public void start() throws Exception { 123 | 124 | try { 125 | broker.bind(ISyncService.class.getSimpleName(), syncService); 126 | logger.info("StackSync Server is ready and waiting for messages..."); 127 | } catch (Exception e) { 128 | logger.fatal("Could not bind queue.", e); 129 | System.exit(5); 130 | } 131 | 132 | logger.info("Initializing XML RPC..."); 133 | try { 134 | launchXmlRpc(); 135 | logger.info("XML RPC initialization succeded"); 136 | } catch (Exception e) { 137 | logger.fatal("Could not initialize XMLRPC.", e); 138 | System.exit(6); 139 | } 140 | } 141 | 142 | @Override 143 | public void stop() throws Exception { 144 | try { 145 | broker.stopBroker(); 146 | } catch (Exception e) { 147 | logger.fatal("Error stoping StackSync Server.", e); 148 | throw e; 149 | } 150 | } 151 | 152 | @Override 153 | public void destroy() { 154 | broker = null; 155 | } 156 | 157 | private static void launchXmlRpc() throws Exception { 158 | xmlRpcServer = new XmlRpcSyncServer(Constants.XMLRPC_PORT); 159 | xmlRpcServer.addHandler("XmlRpcSyncHandler", new XmlRpcSyncHandler( 160 | broker, pool)); 161 | xmlRpcServer.serve_forever(); 162 | } 163 | 164 | private static String getVersion() { 165 | String path = "/version.properties"; 166 | InputStream stream = Config.class.getResourceAsStream(path); 167 | if (stream == null) { 168 | return "UNKNOWN"; 169 | } 170 | Properties props = new Properties(); 171 | try { 172 | props.load(stream); 173 | stream.close(); 174 | return (String) props.get("version"); 175 | } catch (IOException e) { 176 | return "UNKNOWN"; 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/ConnectionPool.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | 6 | public abstract class ConnectionPool { 7 | 8 | public abstract Connection getConnection() throws SQLException; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/ConnectionPoolFactory.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | import com.stacksync.syncservice.db.postgresql.PostgresqlConnectionPool; 6 | import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException; 7 | import com.stacksync.syncservice.util.Config; 8 | 9 | public class ConnectionPoolFactory { 10 | private static final Logger logger = Logger.getLogger(ConnectionPoolFactory.class.getName()); 11 | 12 | public static ConnectionPool getConnectionPool(String datasource) throws DAOConfigurationException { 13 | 14 | if ("postgresql".equalsIgnoreCase(datasource)) { 15 | // Obtain info 16 | String host = Config.getPostgresqlHost(); 17 | Integer port = Config.getPostgresqlPort(); 18 | String database = Config.getPostgresqlDatabase(); 19 | String password = Config.getPostgresqlPassword(); 20 | String username = Config.getPostgresqlUsername(); 21 | int initialConns = Config.getPostgresqlInitialConns(); 22 | int maxConns = Config.getPostgresqlMaxConns(); 23 | 24 | // 25 | return new PostgresqlConnectionPool(host, port, database, username, password, initialConns, maxConns); 26 | } 27 | 28 | logger.error("Could not find any driver matching your request"); 29 | throw new DAOConfigurationException("Driver not found"); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/DAOError.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | public enum DAOError { 4 | 5 | // These errors codes correspond to HTTP codes 6 | // Users 7 | USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401, 8 | "The user is not authorized to access to this resource."), 9 | 10 | // Workspaces 11 | WORKSPACES_NOT_FOUND(410, "Workspaces not found."), 12 | 13 | // Files 14 | FILE_NOT_FOUND(404, "File or folder not found."), 15 | 16 | // Server 17 | INTERNAL_SERVER_ERROR(500, "Internal Server Error"); 18 | 19 | private final int code; 20 | private final String message; 21 | 22 | DAOError(int code, String message) { 23 | this.code = code; 24 | this.message = message; 25 | } 26 | 27 | public int getCode() { 28 | return code; 29 | } 30 | 31 | public String getMessage() { 32 | return message; 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/DAOFactory.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.sql.Connection; 4 | 5 | import com.stacksync.syncservice.db.postgresql.PostgresqlDeviceDAO; 6 | import com.stacksync.syncservice.db.postgresql.PostgresqlItemDAO; 7 | import com.stacksync.syncservice.db.postgresql.PostgresqlItemVersionDao; 8 | import com.stacksync.syncservice.db.postgresql.PostgresqlUserDAO; 9 | import com.stacksync.syncservice.db.postgresql.PostgresqlWorkspaceDAO; 10 | 11 | public class DAOFactory { 12 | 13 | private String type; 14 | 15 | public DAOFactory(String type) { 16 | this.type = type; 17 | } 18 | 19 | public WorkspaceDAO getWorkspaceDao(Connection connection) { 20 | return new PostgresqlWorkspaceDAO(connection); 21 | } 22 | 23 | public UserDAO getUserDao(Connection connection) { 24 | return new PostgresqlUserDAO(connection); 25 | } 26 | 27 | public ItemDAO getItemDAO(Connection connection) { 28 | return new PostgresqlItemDAO(connection); 29 | } 30 | 31 | public ItemVersionDAO getItemVersionDAO(Connection connection) { 32 | return new PostgresqlItemVersionDao(connection); 33 | } 34 | 35 | public DeviceDAO getDeviceDAO(Connection connection) { 36 | return new PostgresqlDeviceDAO(connection); 37 | } 38 | 39 | public String getType() { 40 | return type; 41 | } 42 | 43 | public void setType(String type) { 44 | this.type = type; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/DeviceDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.util.UUID; 4 | 5 | import com.stacksync.commons.models.Device; 6 | import com.stacksync.syncservice.exceptions.dao.DAOException; 7 | 8 | public interface DeviceDAO { 9 | 10 | public Device get(UUID id) throws DAOException; 11 | 12 | public void add(Device device) throws DAOException; 13 | 14 | public void update(Device device) throws DAOException; 15 | 16 | public void delete(UUID id) throws DAOException; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/ItemDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.util.List; 4 | import java.util.UUID; 5 | 6 | import com.stacksync.commons.models.Item; 7 | import com.stacksync.commons.models.ItemMetadata; 8 | import com.stacksync.syncservice.exceptions.dao.DAOException; 9 | 10 | public interface ItemDAO { 11 | public Item findById(Long id) throws DAOException; 12 | 13 | public void add(Item item) throws DAOException; 14 | 15 | public void update(Item item) throws DAOException; 16 | 17 | public void put(Item item) throws DAOException; 18 | 19 | public void delete(Long id) throws DAOException; 20 | 21 | // ItemMetadata information 22 | public List getItemsByWorkspaceId(UUID workspaceId) throws DAOException; 23 | 24 | public List getItemsById(Long id) throws DAOException; 25 | 26 | public ItemMetadata findById(Long id, Boolean includeList, Long version, Boolean includeDeleted, Boolean includeChunks) throws DAOException; 27 | 28 | public ItemMetadata findByUserId(UUID serverUserId, Boolean includeDeleted) throws DAOException; 29 | 30 | public ItemMetadata findItemVersionsById(Long id) throws DAOException; 31 | 32 | public List migrateItem(Long itemId, UUID workspaceId) throws DAOException; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/ItemVersionDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.util.List; 4 | 5 | import com.stacksync.commons.models.Chunk; 6 | import com.stacksync.commons.models.ItemMetadata; 7 | import com.stacksync.commons.models.ItemVersion; 8 | import com.stacksync.syncservice.exceptions.dao.DAOException; 9 | 10 | public interface ItemVersionDAO { 11 | 12 | public ItemMetadata findByItemIdAndVersion(Long id, Long version) throws DAOException;; 13 | 14 | public void add(ItemVersion itemVersion) throws DAOException; 15 | 16 | public void insertChunk(Long itemVersionId, Long chunkId, Integer order) throws DAOException; 17 | 18 | public void insertChunks(List chunks, long itemVersionId) throws DAOException; 19 | 20 | public List findChunks(Long itemVersionId) throws DAOException; 21 | 22 | public void update(ItemVersion itemVersion) throws DAOException; 23 | 24 | public void delete(ItemVersion itemVersion) throws DAOException; 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/UserDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.util.List; 4 | import java.util.UUID; 5 | 6 | import com.stacksync.commons.models.User; 7 | import com.stacksync.syncservice.exceptions.dao.DAOException; 8 | 9 | public interface UserDAO { 10 | 11 | public User findById(UUID id) throws DAOException; 12 | 13 | public User getByEmail(String email) throws DAOException; 14 | 15 | public List findAll() throws DAOException; 16 | 17 | public List findByItemId(Long clientFileId) throws DAOException; 18 | 19 | public void add(User user) throws DAOException; 20 | 21 | public void update(User user) throws DAOException; 22 | 23 | public void delete(UUID id) throws DAOException; 24 | 25 | public void updateAvailableQuota(User user) throws DAOException; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/WorkspaceDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db; 2 | 3 | import java.util.List; 4 | import java.util.UUID; 5 | 6 | import com.stacksync.commons.models.User; 7 | import com.stacksync.commons.models.UserWorkspace; 8 | import com.stacksync.commons.models.Workspace; 9 | import com.stacksync.syncservice.exceptions.dao.DAOException; 10 | 11 | public interface WorkspaceDAO { 12 | 13 | public Workspace getById(UUID id) throws DAOException; 14 | 15 | public List getByUserId(UUID userId) throws DAOException; 16 | 17 | public Workspace getDefaultWorkspaceByUserId(UUID userId) throws DAOException; 18 | 19 | public Workspace getByItemId(Long itemId) throws DAOException; 20 | 21 | public void add(Workspace workspace) throws DAOException; 22 | 23 | public void update(User user, Workspace workspace) throws DAOException; 24 | 25 | public void addUser(User user, Workspace workspace) throws DAOException; 26 | 27 | public void deleteUser(User user, Workspace workspace) throws DAOException; 28 | 29 | public void delete(UUID id) throws DAOException; 30 | 31 | public List getMembersById(UUID workspaceId) throws DAOException; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlConnectionPool.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db.postgresql; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | 6 | import org.postgresql.ds.PGPoolingDataSource; 7 | 8 | import com.stacksync.syncservice.db.ConnectionPool; 9 | import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException; 10 | 11 | public class PostgresqlConnectionPool extends ConnectionPool { 12 | 13 | private PGPoolingDataSource source; 14 | 15 | public PostgresqlConnectionPool(String host, int port, String database, String username, String password, int initialConns, int maxConns) 16 | throws DAOConfigurationException { 17 | try { 18 | Class.forName("org.postgresql.Driver"); 19 | 20 | // Initialize a pooling DataSource 21 | source = new PGPoolingDataSource(); 22 | source.setDatabaseName(database); 23 | source.setServerName(host); 24 | source.setPortNumber(port); 25 | source.setUser(username); 26 | source.setPassword(password); 27 | source.setInitialConnections(initialConns); 28 | source.setMaxConnections(maxConns); 29 | source.getConnection().close(); 30 | 31 | } catch (ClassNotFoundException e) { 32 | throw new DAOConfigurationException("PostgreSQL JDBC driver not found", e); 33 | } catch (SQLException e) { 34 | throw new DAOConfigurationException("SQLException catched at DAOFactory", e); 35 | } 36 | 37 | } 38 | 39 | @Override 40 | public synchronized Connection getConnection() throws SQLException { 41 | try { 42 | return source.getConnection(); 43 | } catch (Exception e) { 44 | throw new SQLException(e); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db.postgresql; 2 | 3 | import static com.stacksync.syncservice.db.DAOUtil.prepareStatement; 4 | 5 | import java.sql.Connection; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | 10 | import org.apache.log4j.Logger; 11 | 12 | import com.stacksync.syncservice.db.DAOError; 13 | import com.stacksync.syncservice.exceptions.dao.DAOException; 14 | import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; 15 | 16 | public class PostgresqlDAO { 17 | private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName()); 18 | protected Connection connection; 19 | 20 | public PostgresqlDAO(Connection connection) { 21 | this.connection = connection; 22 | } 23 | 24 | protected ResultSet executeQuery(String query, Object[] values) throws DAOException { 25 | 26 | PreparedStatement preparedStatement = null; 27 | ResultSet resultSet = null; 28 | 29 | try { 30 | preparedStatement = prepareStatement(connection, query, false, values); 31 | resultSet = preparedStatement.executeQuery(); 32 | 33 | } catch (SQLException e) { 34 | logger.error(e); 35 | throw new DAOException(e, DAOError.INTERNAL_SERVER_ERROR); 36 | } 37 | 38 | return resultSet; 39 | } 40 | 41 | protected Object executeUpdate(String query, Object[] values) throws DAOException { 42 | 43 | Object key = null; 44 | PreparedStatement preparedStatement = null; 45 | ResultSet generatedKeys = null; 46 | 47 | try { 48 | preparedStatement = prepareStatement(connection, query, true, values); 49 | int affectedRows = preparedStatement.executeUpdate(); 50 | if (affectedRows == 0) { 51 | throw new NoRowsAffectedDAOException("Execute update error: no rows affected."); 52 | } 53 | 54 | if (query.startsWith("INSERT")) { 55 | generatedKeys = preparedStatement.getGeneratedKeys(); 56 | 57 | if (generatedKeys.next()) { 58 | key = generatedKeys.getObject(1); 59 | } else { 60 | throw new DAOException("Creating object failed, no generated key obtained."); 61 | } 62 | } 63 | 64 | } catch (SQLException e) { 65 | logger.error(e); 66 | throw new DAOException(e, DAOError.INTERNAL_SERVER_ERROR); 67 | } 68 | 69 | return key; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDeviceDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db.postgresql; 2 | 3 | import java.sql.Connection; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.util.UUID; 7 | 8 | import org.apache.log4j.Logger; 9 | 10 | import com.stacksync.commons.models.Device; 11 | import com.stacksync.commons.models.User; 12 | import com.stacksync.syncservice.db.DeviceDAO; 13 | import com.stacksync.syncservice.exceptions.dao.DAOException; 14 | import com.stacksync.syncservice.util.Constants; 15 | 16 | public class PostgresqlDeviceDAO extends PostgresqlDAO implements DeviceDAO { 17 | 18 | private static final Logger logger = Logger.getLogger(PostgresqlDeviceDAO.class.getName()); 19 | 20 | public PostgresqlDeviceDAO(Connection connection) { 21 | super(connection); 22 | } 23 | 24 | @Override 25 | public Device get(UUID deviceID) throws DAOException { 26 | 27 | // API device ID is not stored in the database 28 | if(deviceID == Constants.API_DEVICE_ID){ 29 | return new Device(Constants.API_DEVICE_ID); 30 | } 31 | 32 | ResultSet resultSet = null; 33 | Device device = null; 34 | 35 | String query = "SELECT * FROM device WHERE id = ?::uuid"; 36 | 37 | try { 38 | resultSet = executeQuery(query, new Object[] { deviceID }); 39 | 40 | if (resultSet.next()) { 41 | device = mapDevice(resultSet); 42 | } 43 | } catch (SQLException e) { 44 | throw new DAOException(e); 45 | } 46 | 47 | return device; 48 | } 49 | 50 | @Override 51 | public void add(Device device) throws DAOException { 52 | if (!device.isValid()) { 53 | throw new IllegalArgumentException("Device attributes not set"); 54 | } 55 | 56 | Object[] values = { device.getName(), device.getUser().getId(), device.getOs(), 57 | device.getLastIp(), device.getAppVersion() }; 58 | 59 | String query = "INSERT INTO device (name, user_id, os, created_at, last_access_at, last_ip, app_version) " 60 | + "VALUES (?, ?::uuid, ?, now(), now(), ?::inet, ?)"; 61 | 62 | UUID id = (UUID) executeUpdate(query, values); 63 | 64 | if (id != null) { 65 | device.setId(id); 66 | } 67 | } 68 | 69 | @Override 70 | public void update(Device device) throws DAOException { 71 | if (device.getId() == null || !device.isValid()) { 72 | throw new IllegalArgumentException("Device attributes not set"); 73 | } 74 | 75 | Object[] values = { device.getLastIp(), device.getAppVersion(), device.getId(), device.getUser().getId() }; 76 | 77 | String query = "UPDATE device SET last_access_at = now(), last_ip = ?::inet, app_version = ? " 78 | + "WHERE id = ?::uuid and user_id = ?::uuid"; 79 | 80 | try { 81 | executeUpdate(query, values); 82 | } catch (DAOException e) { 83 | logger.error(e); 84 | throw new DAOException(e); 85 | } 86 | } 87 | 88 | @Override 89 | public void delete(UUID deviceID) throws DAOException { 90 | Object[] values = { deviceID }; 91 | 92 | String query = "DELETE FROM device WHERE id = ?::uuid"; 93 | 94 | executeUpdate(query, values); 95 | } 96 | 97 | private Device mapDevice(ResultSet resultSet) throws SQLException { 98 | 99 | Device device = new Device(); 100 | device.setId(UUID.fromString(resultSet.getString("id"))); 101 | device.setName(resultSet.getString("name")); 102 | 103 | User user = new User(); 104 | user.setId(UUID.fromString(resultSet.getString("user_id"))); 105 | 106 | device.setUser(user); 107 | 108 | return device; 109 | 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlItemVersionDao.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db.postgresql; 2 | 3 | import java.sql.Connection; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.apache.log4j.Logger; 10 | 11 | import com.stacksync.commons.models.Chunk; 12 | import com.stacksync.commons.models.ItemMetadata; 13 | import com.stacksync.commons.models.ItemVersion; 14 | import com.stacksync.syncservice.db.DAOError; 15 | import com.stacksync.syncservice.db.DAOUtil; 16 | import com.stacksync.syncservice.db.ItemVersionDAO; 17 | import com.stacksync.syncservice.exceptions.dao.DAOException; 18 | 19 | public class PostgresqlItemVersionDao extends PostgresqlDAO implements ItemVersionDAO { 20 | 21 | private static final Logger logger = Logger.getLogger(PostgresqlItemVersionDao.class.getName()); 22 | 23 | public PostgresqlItemVersionDao(Connection connection) { 24 | super(connection); 25 | } 26 | 27 | @Override 28 | public ItemMetadata findByItemIdAndVersion(Long id, Long version) throws DAOException { 29 | Object[] values = { id, version }; 30 | 31 | String query = "SELECT i.id AS item_id, i.parent_id, i.client_parent_file_version, i.filename, i.is_folder, i.mimetype, i.workspace_id, " 32 | + " iv.version, iv.device_id, iv.checksum, iv.status, iv.size, iv.modified_at, " 33 | + " get_chunks(iv.id) AS chunks " 34 | + " FROM item_version iv " 35 | + " INNER JOIN item i ON i.id = iv.item_id " 36 | + " WHERE iv.item_id = ? and iv.version = ?"; 37 | 38 | ResultSet result = null; 39 | ItemMetadata metadata = null; 40 | 41 | try { 42 | 43 | result = executeQuery(query, values); 44 | 45 | if (result.next()) { 46 | 47 | metadata = DAOUtil.getItemMetadataFromResultSet(result); 48 | } else { 49 | // TODO error, no ha encontrado nada el perroo 50 | // throw workspace not found?? 51 | } 52 | 53 | } catch (SQLException e) { 54 | logger.error(e); 55 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 56 | } 57 | 58 | return metadata; 59 | } 60 | 61 | @Override 62 | public void add(ItemVersion itemVersion) throws DAOException { 63 | if (!itemVersion.isValid()) { 64 | throw new IllegalArgumentException("Item version attributes not set"); 65 | } 66 | 67 | Object[] values = { itemVersion.getItem().getId(), itemVersion.getDevice().getId(), itemVersion.getVersion(), 68 | itemVersion.getChecksum(), itemVersion.getStatus(), itemVersion.getSize(), 69 | new java.sql.Timestamp(itemVersion.getModifiedAt().getTime()) }; 70 | 71 | String query = "INSERT INTO item_version( item_id, device_id, version, " 72 | + "checksum, status, size, modified_at, committed_at ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?, now() )"; 73 | 74 | Long id = (Long)executeUpdate(query, values); 75 | 76 | if (id != null) { 77 | itemVersion.setId(id); 78 | } 79 | 80 | } 81 | 82 | @Override 83 | public void update(ItemVersion itemVersion) throws DAOException { 84 | // TODO Auto-generated method stub 85 | 86 | } 87 | 88 | @Override 89 | public void delete(ItemVersion itemVersion) throws DAOException { 90 | // TODO Auto-generated method stub 91 | 92 | } 93 | 94 | @Override 95 | public void insertChunk(Long itemVersionId, Long chunkId, Integer order) throws DAOException { 96 | Object[] values = { itemVersionId, chunkId, order }; 97 | 98 | String query = "INSERT INTO item_version_chunk( item_version_id, chunk_id, chunk_order ) " 99 | + "VALUES ( ?, ?, ? )"; 100 | 101 | try { 102 | executeUpdate(query, values); 103 | } catch (DAOException e) { 104 | logger.error(e); 105 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 106 | } 107 | } 108 | 109 | @Override 110 | public void insertChunks(List chunks, long itemVersionId) throws DAOException { 111 | if (chunks.isEmpty()) { 112 | throw new IllegalArgumentException("No chunks received"); 113 | } 114 | 115 | List values = new ArrayList(); 116 | 117 | StringBuilder build = new StringBuilder("INSERT INTO item_version_chunk " 118 | + " (item_version_id, client_chunk_name, chunk_order) VALUES "); 119 | 120 | for (int i = 0; i < chunks.size(); i++) { 121 | build.append("(?, ?, ?)"); 122 | if (i < chunks.size() - 1) { 123 | build.append(", "); 124 | } else { 125 | build.append(";"); 126 | } 127 | 128 | values.add(itemVersionId); // item_version_id 129 | values.add(chunks.get(i).getClientChunkName()); // client_chunk_name 130 | values.add(i + 1); // chunk_order 131 | } 132 | 133 | try { 134 | executeUpdate(build.toString(), values.toArray()); 135 | 136 | } catch (DAOException ex) { 137 | throw new DAOException(ex); 138 | } 139 | } 140 | 141 | @Override 142 | public List findChunks(Long itemVersionId) throws DAOException { 143 | Object[] values = { itemVersionId }; 144 | 145 | String query = "SELECT ivc.* " + " FROM item_version_chunk ivc " + " WHERE ivc.item_version_id=? " 146 | + " ORDER BY ivc.chunk_order ASC"; 147 | 148 | ResultSet result = null; 149 | List chunks = new ArrayList(); 150 | 151 | try { 152 | result = executeQuery(query, values); 153 | 154 | while (result.next()) { 155 | Chunk chunk = DAOUtil.getChunkFromResultSet(result); 156 | chunks.add(chunk); 157 | } 158 | 159 | } catch (SQLException e) { 160 | logger.error(e); 161 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 162 | } 163 | 164 | return chunks; 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.db.postgresql; 2 | 3 | import java.sql.Connection; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.UUID; 9 | 10 | import org.apache.log4j.Logger; 11 | 12 | import com.stacksync.commons.models.User; 13 | import com.stacksync.syncservice.db.DAOError; 14 | import com.stacksync.syncservice.db.UserDAO; 15 | import com.stacksync.syncservice.exceptions.dao.DAOException; 16 | import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException; 17 | 18 | public class PostgresqlUserDAO extends PostgresqlDAO implements UserDAO { 19 | private static final Logger logger = Logger.getLogger(PostgresqlUserDAO.class.getName()); 20 | 21 | public PostgresqlUserDAO(Connection connection) { 22 | super(connection); 23 | } 24 | 25 | @Override 26 | public User findById(UUID userID) throws DAOException { 27 | ResultSet resultSet = null; 28 | User user = null; 29 | 30 | String query = "SELECT id, name, email, swift_user, swift_account, quota_limit, quota_used_logical, quota_used_real " + " FROM \"user1\" WHERE id = ?::uuid"; 31 | 32 | try { 33 | resultSet = executeQuery(query, new Object[] { userID }); 34 | 35 | if (resultSet.next()) { 36 | user = mapUser(resultSet); 37 | } 38 | } catch (SQLException e) { 39 | logger.error(e); 40 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 41 | } 42 | 43 | if (user == null){ 44 | throw new DAOException(DAOError.USER_NOT_FOUND); 45 | } 46 | 47 | return user; 48 | } 49 | 50 | @Override 51 | public User getByEmail(String email) throws DAOException { 52 | 53 | ResultSet resultSet = null; 54 | User user = null; 55 | 56 | String query = "SELECT * " + " FROM \"user1\" WHERE email = lower(?)"; 57 | 58 | try { 59 | resultSet = executeQuery(query, new Object[] { email }); 60 | 61 | if (resultSet.next()) { 62 | user = mapUser(resultSet); 63 | }else{ 64 | throw new NoResultReturnedDAOException(DAOError.USER_NOT_FOUND); 65 | } 66 | } catch (SQLException e) { 67 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 68 | } 69 | 70 | return user; 71 | } 72 | 73 | @Override 74 | public List findAll() throws DAOException { 75 | 76 | ResultSet resultSet = null; 77 | List list = new ArrayList(); 78 | 79 | String query = "SELECT * FROM user1"; 80 | try { 81 | resultSet = executeQuery(query, null); 82 | 83 | while (resultSet.next()) { 84 | list.add(mapUser(resultSet)); 85 | } 86 | } catch (SQLException e) { 87 | logger.error(e); 88 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 89 | } 90 | return list; 91 | } 92 | 93 | @Override 94 | public void add(User user) throws DAOException { 95 | if (!user.isValid()) { 96 | throw new IllegalArgumentException("User attributes not set"); 97 | } 98 | 99 | Object[] values = { user.getEmail(), user.getName(), user.getSwiftUser(), user.getSwiftAccount(), user.getQuotaLimit(), user.getQuotaUsedLogical(), user.getQuotaUsedReal() }; 100 | 101 | String query = "INSERT INTO user1 (email, name, swift_user, swift_account, quota_limit, quota_used_logical, quota_used_real) VALUES (?, ?, ?, ?, ?, ?)"; 102 | 103 | try { 104 | UUID userId = (UUID) executeUpdate(query, values); 105 | user.setId(userId); 106 | } catch (DAOException e) { 107 | logger.error(e); 108 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 109 | } 110 | } 111 | 112 | @Override 113 | public void update(User user) throws DAOException { 114 | if (user.getId() == null || !user.isValid()) { 115 | throw new IllegalArgumentException("User attributes not set"); 116 | } 117 | 118 | Object[] values = { user.getEmail(), user.getName(), user.getSwiftUser(), user.getSwiftAccount(), user.getQuotaLimit(), user.getQuotaUsedLogical(), user.getQuotaUsedReal(), user.getId() }; 119 | 120 | String query = "UPDATE user1 SET email = ?, name = ?, swift_user = ?, swift_account = ?, quota_limit = ?, quota_used_logical = ?, quota_used_real = ? WHERE id = ?::uuid"; 121 | 122 | try { 123 | executeUpdate(query, values); 124 | } catch (DAOException e) { 125 | logger.error(e); 126 | throw new DAOException(e); 127 | } 128 | } 129 | 130 | 131 | @Override 132 | public void delete(UUID userID) throws DAOException { 133 | Object[] values = { userID }; 134 | 135 | String query = "DELETE FROM user1 WHERE id = ?"; 136 | 137 | executeUpdate(query, values); 138 | } 139 | 140 | private User mapUser(ResultSet resultSet) throws SQLException { 141 | User user = new User(); 142 | user.setId(UUID.fromString(resultSet.getString("id"))); 143 | user.setEmail(resultSet.getString("email")); 144 | user.setName(resultSet.getString("name")); 145 | user.setSwiftUser(resultSet.getString("swift_user")); 146 | user.setSwiftAccount(resultSet.getString("swift_account")); 147 | user.setQuotaLimit(resultSet.getLong("quota_limit")); 148 | user.setQuotaUsedLogical(resultSet.getLong("quota_used_logical")); 149 | user.setQuotaUsedReal(resultSet.getLong("quota_used_real")); 150 | return user; 151 | } 152 | 153 | @Override 154 | public List findByItemId(Long itemId) throws DAOException { 155 | ArrayList users = new ArrayList(); 156 | Object[] values = { itemId }; 157 | 158 | String query = "SELECT u.* " 159 | + " FROM item i " 160 | + " INNER JOIN workspace_user wu ON i.workspace_id = wu.workspace_id " 161 | + " INNER JOIN user1 u ON wu.user_id = u.id " 162 | + " WHERE i.id = ?"; 163 | 164 | ResultSet result = null; 165 | 166 | try { 167 | result = executeQuery(query, values); 168 | 169 | while (result.next()) { 170 | User user = mapUser(result); 171 | users.add(user); 172 | } 173 | 174 | } catch (SQLException e) { 175 | logger.error(e); 176 | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); 177 | } 178 | 179 | return users; 180 | } 181 | 182 | @Override 183 | public void updateAvailableQuota(User user) throws DAOException { 184 | // TODO Auto-generated method stub 185 | if (user.getId() == null || !user.isValid()) { 186 | throw new IllegalArgumentException("User attributes not set"); 187 | } 188 | 189 | Object[] values = {user.getQuotaUsedLogical(), user.getId()}; 190 | 191 | String query = "UPDATE user1 SET quota_used_logical = ? WHERE id = ?::uuid"; 192 | 193 | try { 194 | executeUpdate(query, values); 195 | } catch (DAOException e) { 196 | logger.error(e); 197 | throw new DAOException(e); 198 | } 199 | 200 | } 201 | 202 | 203 | 204 | } 205 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/CommitExistantVersion.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions; 2 | 3 | import com.stacksync.commons.models.Item; 4 | 5 | public class CommitExistantVersion extends Exception { 6 | 7 | private static final long serialVersionUID = 3790965344729620693L; 8 | 9 | private Item item; 10 | private long version; 11 | 12 | public CommitExistantVersion() { 13 | super(); 14 | } 15 | 16 | public CommitExistantVersion(String message) { 17 | super(message); 18 | } 19 | 20 | public CommitExistantVersion(String message, Item item, long version) { 21 | super(message); 22 | this.item = item; 23 | this.version = version; 24 | } 25 | 26 | public CommitExistantVersion(String message, Throwable cause) { 27 | super(message, cause); 28 | } 29 | 30 | public CommitExistantVersion(Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | public Item getItem() { 35 | return item; 36 | } 37 | 38 | public long getVersion() { 39 | return version; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/CommitWrongVersion.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions; 2 | 3 | import com.stacksync.commons.models.Item; 4 | 5 | public class CommitWrongVersion extends Exception { 6 | 7 | private static final long serialVersionUID = 632312815010044106L; 8 | private Item item; 9 | 10 | public CommitWrongVersion() { 11 | super(); 12 | } 13 | 14 | public CommitWrongVersion(String message) { 15 | super(message); 16 | } 17 | 18 | public CommitWrongVersion(String message, Item item) { 19 | super(message); 20 | this.item = item; 21 | } 22 | 23 | public CommitWrongVersion(String message, Throwable cause) { 24 | super(message, cause); 25 | } 26 | 27 | public CommitWrongVersion(Throwable cause) { 28 | super(cause); 29 | } 30 | 31 | public Item getItem() { 32 | return item; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/InternalServerError.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions; 2 | 3 | public class InternalServerError extends Exception { 4 | 5 | private static final long serialVersionUID = 7240966151447816363L; 6 | 7 | public InternalServerError() { 8 | super(); 9 | } 10 | 11 | public InternalServerError(String message) { 12 | super(message); 13 | } 14 | 15 | public InternalServerError(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public InternalServerError(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/InvalidReader.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions; 2 | 3 | public class InvalidReader extends Exception { 4 | 5 | private static final long serialVersionUID = 3910376966796379039L; 6 | 7 | public InvalidReader() { 8 | super(); 9 | } 10 | 11 | public InvalidReader(String message) { 12 | super(message); 13 | } 14 | 15 | public InvalidReader(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public InvalidReader(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/NotEnoughConsumersException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions; 2 | 3 | public class NotEnoughConsumersException extends Exception { 4 | 5 | private static final long serialVersionUID = -3470994628999546970L; 6 | 7 | public NotEnoughConsumersException() { 8 | super(); 9 | } 10 | 11 | public NotEnoughConsumersException(String message) { 12 | super(message); 13 | } 14 | 15 | public NotEnoughConsumersException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public NotEnoughConsumersException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/dao/DAOConfigurationException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.dao; 2 | 3 | /** 4 | * This class represents an exception in the DAO configuration which cannot be resolved at runtime, 5 | * such as a missing resource in the classpath, a missing property in the properties file, etcetera. 6 | * 7 | * @author BalusC 8 | * @link http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html 9 | */ 10 | public class DAOConfigurationException extends Exception { 11 | 12 | // Constants ---------------------------------------------------------------------------------- 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | // Constructors ------------------------------------------------------------------------------- 17 | 18 | /** 19 | * Constructs a DAOConfigurationException with the given detail message. 20 | * @param message The detail message of the DAOConfigurationException. 21 | */ 22 | public DAOConfigurationException(String message) { 23 | super(message); 24 | } 25 | 26 | /** 27 | * Constructs a DAOConfigurationException with the given root cause. 28 | * @param cause The root cause of the DAOConfigurationException. 29 | */ 30 | public DAOConfigurationException(Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | /** 35 | * Constructs a DAOConfigurationException with the given detail message and root cause. 36 | * @param message The detail message of the DAOConfigurationException. 37 | * @param cause The root cause of the DAOConfigurationException. 38 | */ 39 | public DAOConfigurationException(String message, Throwable cause) { 40 | super(message, cause); 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.dao; 2 | 3 | import com.stacksync.syncservice.db.DAOError; 4 | 5 | /** 6 | * This class represents a generic DAO exception. It should wrap any exception on the database level 7 | * , such as SQLExceptions. 8 | */ 9 | public class DAOException extends Exception { 10 | 11 | private static final long serialVersionUID = 1L; 12 | private DAOError error; 13 | /** 14 | * Constructs a DAOException with the given detail message. 15 | * @param message The detail message of the DAOException. 16 | */ 17 | public DAOException(DAOError error) { 18 | super(error.getMessage()); 19 | this.error = error; 20 | } 21 | 22 | public DAOException(Exception e, DAOError error) { 23 | super(e); 24 | this.error = error; 25 | } 26 | 27 | public DAOException(String message) { 28 | super(message); 29 | } 30 | 31 | public DAOError getError(){ 32 | return this.error; 33 | } 34 | /** 35 | * Constructs a DAOException with the given root cause. 36 | * @param cause The root cause of the DAOException. 37 | */ 38 | public DAOException(Throwable cause) { 39 | super(cause); 40 | } 41 | 42 | /** 43 | * Constructs a DAOException with the given detail message and root cause. 44 | * @param message The detail message of the DAOException. 45 | * @param cause The root cause of the DAOException. 46 | */ 47 | public DAOException(String message, Throwable cause) { 48 | super(message, cause); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/dao/NoGeneratedKeysDAOException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.dao; 2 | 3 | import com.stacksync.syncservice.db.DAOError; 4 | 5 | public class NoGeneratedKeysDAOException extends DAOException { 6 | 7 | private static final long serialVersionUID = -2938093497450050090L; 8 | 9 | public NoGeneratedKeysDAOException(DAOError error) { 10 | super(error); 11 | } 12 | 13 | public NoGeneratedKeysDAOException(Exception e, DAOError error) { 14 | super(e, error); 15 | } 16 | 17 | public NoGeneratedKeysDAOException(String message) { 18 | super(message); 19 | } 20 | 21 | public NoGeneratedKeysDAOException(Throwable cause) { 22 | super(cause); 23 | } 24 | 25 | public NoGeneratedKeysDAOException(String message, Throwable cause) { 26 | super(message, cause); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.dao; 2 | 3 | import com.stacksync.syncservice.db.DAOError; 4 | 5 | public class NoResultReturnedDAOException extends DAOException { 6 | 7 | private static final long serialVersionUID = -1412276333572134887L; 8 | 9 | public NoResultReturnedDAOException(DAOError error) { 10 | super(error); 11 | } 12 | 13 | public NoResultReturnedDAOException(Exception e, DAOError error) { 14 | super(e, error); 15 | } 16 | 17 | public NoResultReturnedDAOException(String message) { 18 | super(message); 19 | } 20 | 21 | public NoResultReturnedDAOException(Throwable cause) { 22 | super(cause); 23 | } 24 | 25 | public NoResultReturnedDAOException(String message, Throwable cause) { 26 | super(message, cause); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.dao; 2 | 3 | import com.stacksync.syncservice.db.DAOError; 4 | 5 | public class NoRowsAffectedDAOException extends DAOException { 6 | 7 | private static final long serialVersionUID = 356684827372558709L; 8 | 9 | public NoRowsAffectedDAOException(DAOError error) { 10 | super(error); 11 | } 12 | 13 | public NoRowsAffectedDAOException(Exception e, DAOError error) { 14 | super(e, error); 15 | } 16 | 17 | public NoRowsAffectedDAOException(String message) { 18 | super(message); 19 | } 20 | 21 | public NoRowsAffectedDAOException(Throwable cause) { 22 | super(cause); 23 | } 24 | 25 | public NoRowsAffectedDAOException(String message, Throwable cause) { 26 | super(message, cause); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/storage/EndpointNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.storage; 2 | 3 | public class EndpointNotFoundException extends Exception { 4 | 5 | private static final long serialVersionUID = -2739684204840352075L; 6 | 7 | public EndpointNotFoundException(String message) { 8 | super(message); 9 | } 10 | 11 | public EndpointNotFoundException() { 12 | super(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.storage; 2 | 3 | public class NoStorageManagerAvailable extends Exception { 4 | 5 | private static final long serialVersionUID = -2162586363263343293L; 6 | 7 | public NoStorageManagerAvailable(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/storage/ObjectNotFoundException.java: -------------------------------------------------------------------------------- 1 | 2 | package com.stacksync.syncservice.exceptions.storage; 3 | 4 | public class ObjectNotFoundException extends Exception { 5 | 6 | private static final long serialVersionUID = -5254463856122396229L; 7 | 8 | public ObjectNotFoundException(String message) { 9 | super(message); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/storage/UnauthorizedException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.storage; 2 | 3 | public class UnauthorizedException extends Exception { 4 | 5 | private static final long serialVersionUID = 37491715204419935L; 6 | 7 | public UnauthorizedException(String message) { 8 | super(message); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/exceptions/storage/UnexpectedStatusCodeException.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.exceptions.storage; 2 | 3 | public class UnexpectedStatusCodeException extends Exception { 4 | 5 | private static final long serialVersionUID = 2336051403508530828L; 6 | 7 | public UnexpectedStatusCodeException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/handler/APIHandler.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.handler; 2 | 3 | import java.util.List; 4 | 5 | import com.stacksync.commons.models.Item; 6 | import com.stacksync.commons.models.ItemMetadata; 7 | import com.stacksync.commons.models.User; 8 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 9 | import com.stacksync.syncservice.rpc.messages.APICreateFolderResponse; 10 | import com.stacksync.syncservice.rpc.messages.APIDeleteResponse; 11 | import com.stacksync.syncservice.rpc.messages.APIGetFolderMembersResponse; 12 | import com.stacksync.syncservice.rpc.messages.APIGetMetadata; 13 | import com.stacksync.syncservice.rpc.messages.APIGetVersions; 14 | import com.stacksync.syncservice.rpc.messages.APIGetWorkspaceInfoResponse; 15 | import com.stacksync.syncservice.rpc.messages.APIRestoreMetadata; 16 | import com.stacksync.syncservice.rpc.messages.APIShareFolderResponse; 17 | import com.stacksync.syncservice.rpc.messages.APIUnshareFolderResponse; 18 | 19 | public interface APIHandler { 20 | 21 | public APIGetMetadata getMetadata(User user, Long fileId, Boolean includeChunks, Long version, Boolean isFolder); 22 | 23 | public APICommitResponse createFile(User user, ItemMetadata fileToSave); 24 | 25 | public APICommitResponse updateData(User user, ItemMetadata fileToUpdate); 26 | 27 | public APICommitResponse updateMetadata(User user, ItemMetadata fileToUpdate, Boolean parentUpdated); 28 | 29 | public APICreateFolderResponse createFolder(User user, ItemMetadata item); 30 | 31 | public APIRestoreMetadata restoreMetadata(User user, ItemMetadata item); 32 | 33 | public APIDeleteResponse deleteItem(User user, ItemMetadata item); 34 | 35 | public APIGetVersions getVersions(User user, ItemMetadata item); 36 | 37 | public APIShareFolderResponse shareFolder(User user, Item item, List emails); 38 | 39 | public APIUnshareFolderResponse unshareFolder(User user, Item item, List emails); 40 | 41 | public APIGetWorkspaceInfoResponse getWorkspaceInfo(User user, ItemMetadata item); 42 | 43 | public APIGetFolderMembersResponse getFolderMembers(User user, Item item); 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.handler; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.UUID; 7 | 8 | import org.apache.log4j.Logger; 9 | 10 | import com.stacksync.commons.models.Device; 11 | import com.stacksync.commons.models.ItemMetadata; 12 | import com.stacksync.commons.models.User; 13 | import com.stacksync.commons.models.Workspace; 14 | import com.stacksync.syncservice.db.ConnectionPool; 15 | import com.stacksync.commons.exceptions.DeviceNotUpdatedException; 16 | import com.stacksync.commons.exceptions.DeviceNotValidException; 17 | import com.stacksync.commons.exceptions.NoWorkspacesFoundException; 18 | import com.stacksync.commons.exceptions.UserNotFoundException; 19 | import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException; 20 | import com.stacksync.syncservice.exceptions.dao.DAOException; 21 | import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException; 22 | import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; 23 | import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; 24 | 25 | public class SQLSyncHandler extends Handler implements SyncHandler { 26 | 27 | private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName()); 28 | 29 | public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable { 30 | super(pool); 31 | } 32 | 33 | @Override 34 | public List doGetChanges(User user, Workspace workspace) { 35 | List responseObjects = new ArrayList(); 36 | 37 | try { 38 | responseObjects = itemDao.getItemsByWorkspaceId(workspace.getId()); 39 | } catch (DAOException e) { 40 | logger.error(e.toString(), e); 41 | } 42 | 43 | return responseObjects; 44 | } 45 | 46 | @Override 47 | public List doGetWorkspaces(User user) throws NoWorkspacesFoundException { 48 | 49 | List workspaces = new ArrayList(); 50 | 51 | try { 52 | workspaces = workspaceDAO.getByUserId(user.getId()); 53 | 54 | } catch (NoResultReturnedDAOException e) { 55 | logger.error(e); 56 | throw new NoWorkspacesFoundException(String.format("No workspaces found for user: %s", user.getId())); 57 | } catch (DAOException e) { 58 | logger.error(e); 59 | throw new NoWorkspacesFoundException(e); 60 | } 61 | 62 | return workspaces; 63 | } 64 | 65 | @Override 66 | public UUID doUpdateDevice(Device device) throws UserNotFoundException, DeviceNotValidException, 67 | DeviceNotUpdatedException { 68 | 69 | try { 70 | User dbUser = userDao.findById(device.getUser().getId()); 71 | device.setUser(dbUser); 72 | 73 | } catch (NoResultReturnedDAOException e) { 74 | logger.warn(e); 75 | throw new UserNotFoundException(e); 76 | } catch (DAOException e) { 77 | logger.error(e); 78 | throw new DeviceNotUpdatedException(e); 79 | } 80 | 81 | try { 82 | if (device.getId() == null) { 83 | deviceDao.add(device); 84 | } else { 85 | deviceDao.update(device); 86 | } 87 | } catch (NoRowsAffectedDAOException e) { 88 | logger.error(e); 89 | throw new DeviceNotUpdatedException(e); 90 | } catch (DAOException e) { 91 | logger.error(e); 92 | throw new DeviceNotUpdatedException(e); 93 | } catch (IllegalArgumentException e) { 94 | logger.error(e); 95 | throw new DeviceNotValidException(e); 96 | } 97 | 98 | return device.getId(); 99 | } 100 | 101 | 102 | @Override 103 | public void doUpdateWorkspace(User user, Workspace workspace) throws UserNotFoundException, 104 | WorkspaceNotUpdatedException { 105 | 106 | // Check the owner 107 | try { 108 | user = userDao.findById(user.getId()); 109 | } catch (NoResultReturnedDAOException e) { 110 | logger.warn(e); 111 | throw new UserNotFoundException(e); 112 | } catch (DAOException e) { 113 | logger.error(e); 114 | throw new WorkspaceNotUpdatedException(e); 115 | } 116 | 117 | // Update the workspace 118 | try { 119 | workspaceDAO.update(user, workspace); 120 | } catch (NoRowsAffectedDAOException e) { 121 | logger.error(e); 122 | throw new WorkspaceNotUpdatedException(e); 123 | } catch (DAOException e) { 124 | logger.error(e); 125 | throw new WorkspaceNotUpdatedException(e); 126 | } 127 | } 128 | 129 | @Override 130 | public User doGetUser(String email) throws UserNotFoundException { 131 | 132 | try { 133 | User user = userDao.getByEmail(email); 134 | return user; 135 | 136 | } catch (NoResultReturnedDAOException e) { 137 | logger.error(e); 138 | throw new UserNotFoundException(e); 139 | } catch (DAOException e) { 140 | logger.error(e); 141 | throw new UserNotFoundException(e); 142 | } 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/handler/SyncHandler.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.List; 5 | import java.util.UUID; 6 | 7 | import com.stacksync.commons.models.CommitInfo; 8 | import com.stacksync.commons.models.Device; 9 | import com.stacksync.commons.models.Item; 10 | import com.stacksync.commons.models.ItemMetadata; 11 | import com.stacksync.commons.models.User; 12 | import com.stacksync.commons.models.Workspace; 13 | import com.stacksync.commons.exceptions.DeviceNotUpdatedException; 14 | import com.stacksync.commons.exceptions.DeviceNotValidException; 15 | import com.stacksync.commons.exceptions.NoWorkspacesFoundException; 16 | import com.stacksync.commons.exceptions.ShareProposalNotCreatedException; 17 | import com.stacksync.commons.exceptions.UserNotFoundException; 18 | import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException; 19 | import com.stacksync.commons.notifications.CommitNotification; 20 | import com.stacksync.syncservice.exceptions.dao.DAOException; 21 | 22 | public interface SyncHandler { 23 | 24 | public CommitNotification doCommit(User user, Workspace workspace, Device device, List items) 25 | throws DAOException; 26 | 27 | public List doGetChanges(User user, Workspace workspace); 28 | 29 | public UUID doUpdateDevice(Device device) throws UserNotFoundException, DeviceNotValidException, 30 | DeviceNotUpdatedException; 31 | 32 | public List doGetWorkspaces(User user) throws NoWorkspacesFoundException; 33 | 34 | public Workspace doShareFolder(User user, List emails, Item item, boolean isEncrypted) 35 | throws ShareProposalNotCreatedException, UserNotFoundException; 36 | 37 | public void doUpdateWorkspace(User user, Workspace workspace) throws UserNotFoundException, 38 | WorkspaceNotUpdatedException; 39 | 40 | public User doGetUser(String email) throws UserNotFoundException; 41 | 42 | public Connection getConnection(); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/handler/UnshareData.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.handler; 2 | 3 | 4 | import java.util.List; 5 | 6 | import com.stacksync.commons.models.User; 7 | import com.stacksync.commons.models.Workspace; 8 | 9 | public class UnshareData { 10 | private List usersToRemove; 11 | private Workspace workspace; 12 | private boolean isUnshared; 13 | 14 | public UnshareData(List usersToRemove, Workspace workspace, 15 | boolean isUnshared) { 16 | this.usersToRemove = usersToRemove; 17 | this.workspace = workspace; 18 | this.isUnshared = isUnshared; 19 | } 20 | 21 | public List getUsersToRemove() { 22 | return usersToRemove; 23 | } 24 | 25 | public void setUsersToRemove(List usersToRemove) { 26 | this.usersToRemove = usersToRemove; 27 | } 28 | 29 | public Workspace getWorkspace() { 30 | return workspace; 31 | } 32 | 33 | public void setWorkspace(Workspace workspace) { 34 | this.workspace = workspace; 35 | } 36 | 37 | public boolean isUnshared() { 38 | return isUnshared; 39 | } 40 | 41 | public void setUnshared(boolean isUnshared) { 42 | this.isUnshared = isUnshared; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/Reader.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc; 2 | 3 | import com.stacksync.syncservice.exceptions.InvalidReader; 4 | import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException; 5 | import com.stacksync.syncservice.rpc.parser.IParser; 6 | 7 | public class Reader { 8 | 9 | /** 10 | * @throws DAOConfigurationException 11 | * 12 | */ 13 | public static IParser getInstance(String className) throws InvalidReader { 14 | try { 15 | if (className == null || className.isEmpty()) { 16 | throw new ClassNotFoundException("Class name is null or empty."); 17 | } 18 | 19 | IParser instance = (IParser) Class.forName(className).newInstance(); 20 | return instance; 21 | } catch (Exception ex) { 22 | throw new InvalidReader(ex.getMessage(), ex); 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/XmlRpcRequestHandlerFactory.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.apache.xmlrpc.XmlRpcException; 7 | import org.apache.xmlrpc.XmlRpcRequest; 8 | import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; 9 | import org.apache.xmlrpc.server.RequestProcessorFactoryFactory.RequestProcessorFactory; 10 | 11 | public class XmlRpcRequestHandlerFactory implements RequestProcessorFactoryFactory, RequestProcessorFactory { 12 | 13 | private Map handlerMap = new HashMap(); 14 | 15 | public void setHandler(String name, Object handler) { 16 | this.handlerMap.put(name, handler); 17 | } 18 | 19 | public Object getHandler(String name) { 20 | return this.handlerMap.get(name); 21 | } 22 | 23 | public RequestProcessorFactory getRequestProcessorFactory(@SuppressWarnings("rawtypes") Class arg0) 24 | throws XmlRpcException { 25 | return this; 26 | } 27 | 28 | public Object getRequestProcessor(XmlRpcRequest request) throws XmlRpcException { 29 | 30 | String handlerName = request.getMethodName().substring(0, request.getMethodName().lastIndexOf(".")); 31 | 32 | if (!handlerMap.containsKey(handlerName)) { 33 | throw new XmlRpcException("Unknown handler: " + handlerName); 34 | } 35 | 36 | return handlerMap.get(handlerName); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/XmlRpcSyncServer.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc; 2 | 3 | import org.apache.xmlrpc.server.PropertyHandlerMapping; 4 | import org.apache.xmlrpc.server.XmlRpcServer; 5 | import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; 6 | import org.apache.xmlrpc.webserver.WebServer; 7 | 8 | public class XmlRpcSyncServer { 9 | 10 | private int port; 11 | private WebServer webServer = null; 12 | private PropertyHandlerMapping phm = null; 13 | private XmlRpcRequestHandlerFactory handler = null; 14 | private XmlRpcServer xmlRpcServer = null; 15 | 16 | public XmlRpcSyncServer(int port) throws Exception { 17 | this.port = port; 18 | // bind 19 | this.webServer = new WebServer(this.port); 20 | this.xmlRpcServer = this.webServer.getXmlRpcServer(); 21 | this.handler = new XmlRpcRequestHandlerFactory(); 22 | 23 | this.phm = new PropertyHandlerMapping(); 24 | this.phm.setRequestProcessorFactoryFactory(this.handler); 25 | 26 | } 27 | 28 | public void addHandler(String name, Object requestHandler) throws Exception { 29 | 30 | this.handler.setHandler(name, requestHandler); 31 | this.phm.addHandler(name, requestHandler.getClass()); 32 | 33 | } 34 | 35 | public void serve_forever() throws Exception { 36 | // init 37 | this.xmlRpcServer.setHandlerMapping(phm); 38 | XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); 39 | serverConfig.setEnabledForExtensions(true); 40 | this.webServer.start(); 41 | } 42 | 43 | public int getPort() { 44 | return port; 45 | } 46 | 47 | public void setPort(int port) { 48 | this.port = port; 49 | } 50 | 51 | public WebServer getWebServer() { 52 | return webServer; 53 | } 54 | 55 | public void setWebServer(WebServer webServer) { 56 | this.webServer = webServer; 57 | } 58 | 59 | public PropertyHandlerMapping getPhm() { 60 | return phm; 61 | } 62 | 63 | public void setPhm(PropertyHandlerMapping phm) { 64 | this.phm = phm; 65 | } 66 | 67 | public XmlRpcRequestHandlerFactory getHandler() { 68 | return handler; 69 | } 70 | 71 | public void setHandler(XmlRpcRequestHandlerFactory handler) { 72 | this.handler = handler; 73 | } 74 | 75 | public XmlRpcServer getXmlRpcServer() { 76 | return xmlRpcServer; 77 | } 78 | 79 | public void setXmlRpcServer(XmlRpcServer xmlRpcServer) { 80 | this.xmlRpcServer = xmlRpcServer; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APICommitResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.stacksync.commons.models.CommitInfo; 4 | import com.stacksync.commons.models.ItemMetadata; 5 | 6 | public class APICommitResponse extends APIResponse { 7 | 8 | public APICommitResponse(ItemMetadata item, Boolean success, int error, String description) { 9 | this.success = success; 10 | this.errorCode = error; 11 | this.description = description; 12 | if (item != null) { 13 | this.item = new CommitInfo(item.getVersion(), 14 | success, item); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APICreateFolderResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.stacksync.commons.models.CommitInfo; 4 | import com.stacksync.commons.models.ItemMetadata; 5 | 6 | public class APICreateFolderResponse extends APIResponse { 7 | 8 | public APICreateFolderResponse(ItemMetadata item, Boolean success, int error, String description) { 9 | super(); 10 | this.success = success; 11 | this.errorCode = error; 12 | this.description = description; 13 | if (item != null) { 14 | this.item = new CommitInfo(item.getVersion(), 15 | success, item); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIDeleteResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.stacksync.commons.models.CommitInfo; 4 | import com.stacksync.commons.models.ItemMetadata; 5 | 6 | public class APIDeleteResponse extends APIResponse { 7 | 8 | public APIDeleteResponse(ItemMetadata item, Boolean success, int error, String description) { 9 | super(); 10 | this.success = success; 11 | this.errorCode = error; 12 | this.description = description; 13 | if (item != null) { 14 | this.item = new CommitInfo(item.getVersion(), 15 | success, item); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIGetFolderMembersResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import java.util.List; 4 | 5 | import com.google.gson.JsonArray; 6 | import com.google.gson.JsonObject; 7 | import com.stacksync.commons.models.UserWorkspace; 8 | 9 | public class APIGetFolderMembersResponse extends APIResponse { 10 | 11 | private List members; 12 | 13 | public APIGetFolderMembersResponse(List members, Boolean success, int error, String description) { 14 | super(); 15 | 16 | this.success = success; 17 | this.members = members; 18 | this.description = description; 19 | this.errorCode = error; 20 | } 21 | 22 | public List getMembers() { 23 | return members; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | JsonObject jResponse = new JsonObject(); 29 | 30 | if (getSuccess()) { 31 | 32 | JsonArray list = new JsonArray(); 33 | 34 | for (UserWorkspace userWorkspace : members) { 35 | JsonObject jUser = parseUserWorkspace(userWorkspace); 36 | list.add(jUser); 37 | } 38 | 39 | return list.toString(); 40 | 41 | } else { 42 | jResponse.addProperty("error", getErrorCode()); 43 | jResponse.addProperty("description", getDescription()); 44 | return jResponse.toString(); 45 | } 46 | 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIGetMetadata.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.JsonObject; 5 | import com.stacksync.commons.models.ItemMetadata; 6 | 7 | public class APIGetMetadata extends APIResponse { 8 | 9 | private ItemMetadata itemMetadata; 10 | 11 | public APIGetMetadata(ItemMetadata item, Boolean success, int error, String description) { 12 | super(); 13 | 14 | this.success = success; 15 | this.itemMetadata = item; 16 | this.description = description; 17 | this.errorCode = error; 18 | } 19 | 20 | public ItemMetadata getItemMetadata(){ 21 | return itemMetadata; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | JsonObject jResponse = new JsonObject(); 27 | 28 | if (getSuccess()) { 29 | ItemMetadata metadata = getItemMetadata(); 30 | jResponse = parseObjectMetadataForAPI(metadata); 31 | 32 | if (metadata.getChildren() != null) { 33 | JsonArray contents = new JsonArray(); 34 | 35 | for (ItemMetadata entry : metadata.getChildren()) { 36 | JsonObject entryJson = parseObjectMetadataForAPI(entry); 37 | contents.add(entryJson); 38 | } 39 | 40 | jResponse.add("contents", contents); 41 | } 42 | } else { 43 | jResponse.addProperty("error", getErrorCode()); 44 | jResponse.addProperty("description", getDescription()); 45 | } 46 | 47 | return jResponse.toString(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIGetVersions.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.JsonObject; 5 | import com.stacksync.commons.models.ItemMetadata; 6 | 7 | public class APIGetVersions extends APIResponse { 8 | 9 | private ItemMetadata itemMetadata; 10 | 11 | public APIGetVersions(ItemMetadata item, Boolean success, int error, String description) { 12 | super(); 13 | 14 | this.success = success; 15 | this.itemMetadata = item; 16 | this.description = description; 17 | this.errorCode = error; 18 | } 19 | 20 | public ItemMetadata getItemMetadata(){ 21 | return itemMetadata; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | JsonObject jResponse = new JsonObject(); 27 | 28 | if (getSuccess()) { 29 | ItemMetadata metadata = getItemMetadata(); 30 | jResponse = parseObjectMetadataForAPI(metadata); 31 | 32 | if (metadata.getChildren() != null) { 33 | JsonArray contents = new JsonArray(); 34 | 35 | for (ItemMetadata entry : metadata.getChildren()) { 36 | JsonObject entryJson = parseObjectMetadataForAPI(entry); 37 | contents.add(entryJson); 38 | } 39 | 40 | jResponse.add("versions", contents); 41 | } 42 | } else { 43 | jResponse.addProperty("error", getErrorCode()); 44 | jResponse.addProperty("description", getDescription()); 45 | } 46 | 47 | return jResponse.toString(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIGetWorkspaceInfoResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.google.gson.JsonObject; 4 | import com.stacksync.commons.models.User; 5 | import com.stacksync.commons.models.Workspace; 6 | 7 | public class APIGetWorkspaceInfoResponse extends APIResponse { 8 | 9 | private Workspace workspace; 10 | 11 | public APIGetWorkspaceInfoResponse(Workspace workspace, Boolean success, int error, String description) { 12 | super(); 13 | this.success = success; 14 | this.description = description; 15 | this.errorCode = error; 16 | this.workspace = workspace; 17 | } 18 | 19 | public Workspace getWorkspace() { 20 | return workspace; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | JsonObject jResponse; 26 | 27 | if (!getSuccess()) { 28 | jResponse = new JsonObject(); 29 | jResponse.addProperty("description", getDescription()); 30 | jResponse.addProperty("error", getErrorCode()); 31 | } else { 32 | jResponse = this.parseWorkspace(); 33 | } 34 | 35 | return jResponse.toString(); 36 | } 37 | 38 | protected JsonObject parseWorkspace() { 39 | 40 | JsonObject jMetadata = new JsonObject(); 41 | 42 | if (workspace == null) { 43 | return jMetadata; 44 | } 45 | 46 | jMetadata.addProperty("id", workspace.getId().toString()); 47 | jMetadata.addProperty("name", workspace.getName()); 48 | jMetadata.addProperty("swift_container", workspace.getSwiftContainer()); 49 | jMetadata.addProperty("is_shared", workspace.isShared()); 50 | jMetadata.addProperty("owner", workspace.getOwner().getId().toString()); 51 | jMetadata.addProperty("latest_revision", workspace.getLatestRevision()); 52 | jMetadata.addProperty("parent_item_id", workspace.getParentItem().getId()); 53 | jMetadata.addProperty("is_encrypted", workspace.isEncrypted()); 54 | jMetadata.addProperty("quota_used", workspace.getOwner().getQuotaUsedLogical().toString()); 55 | jMetadata.addProperty("quota_limit", workspace.getOwner().getQuotaLimit().toString()); 56 | 57 | 58 | return jMetadata; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.JsonElement; 5 | import com.google.gson.JsonObject; 6 | import com.google.gson.JsonPrimitive; 7 | import com.stacksync.commons.models.CommitInfo; 8 | import com.stacksync.commons.models.ItemMetadata; 9 | import com.stacksync.commons.models.User; 10 | import com.stacksync.commons.models.UserWorkspace; 11 | 12 | public abstract class APIResponse { 13 | 14 | protected CommitInfo item; 15 | protected Long quotaLimit; 16 | protected Long quotaUsed; 17 | protected Boolean success; 18 | protected int errorCode; 19 | protected String description; 20 | 21 | public Boolean getSuccess() { 22 | return success; 23 | } 24 | 25 | public int getErrorCode() { 26 | return errorCode; 27 | } 28 | 29 | public String getDescription() { 30 | return description; 31 | } 32 | 33 | public CommitInfo getItem() { 34 | return item; 35 | } 36 | 37 | public ItemMetadata getMetadata() { 38 | return item.getMetadata(); 39 | } 40 | 41 | public Long getQuotaLimit() { 42 | return quotaLimit; 43 | } 44 | 45 | public void setQuotaLimit(Long quotaLimit) { 46 | this.quotaLimit = quotaLimit; 47 | } 48 | 49 | public Long getQuotaUsed() { 50 | return quotaUsed; 51 | } 52 | 53 | public void setQuotaUsed(Long quotaUsed) { 54 | this.quotaUsed = quotaUsed; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | JsonObject jResponse; 60 | 61 | if (!getSuccess()) { 62 | jResponse = new JsonObject(); 63 | jResponse.addProperty("error", getErrorCode()); 64 | jResponse.addProperty("description", getDescription()); 65 | } else { 66 | ItemMetadata file = getItem().getMetadata(); 67 | jResponse = this.parseItemMetadata(file); 68 | } 69 | 70 | return jResponse.toString(); 71 | } 72 | 73 | private JsonObject parseItemMetadata(ItemMetadata metadata) { 74 | JsonObject jMetadata = parseMetadata(metadata); 75 | 76 | if (metadata.getParentId() == null) { 77 | jMetadata.addProperty("parent_file_id", ""); 78 | 79 | } else { 80 | jMetadata.addProperty("parent_file_id", metadata.getParentId()); 81 | } 82 | 83 | if (metadata.getParentId() == null) { 84 | jMetadata.addProperty("parent_file_version", ""); 85 | } else { 86 | jMetadata.addProperty("parent_file_version", metadata.getParentVersion()); 87 | } 88 | 89 | // TODO: send only chunks when is a file 90 | if (!metadata.isFolder()) { 91 | JsonArray chunks = new JsonArray(); 92 | for (String chunk : metadata.getChunks()) { 93 | JsonElement elem = new JsonPrimitive(chunk); 94 | chunks.add(elem); 95 | } 96 | jMetadata.add("chunks", chunks); 97 | } 98 | 99 | return jMetadata; 100 | } 101 | 102 | protected JsonObject parseObjectMetadataForAPI(ItemMetadata metadata) { 103 | JsonObject jMetadata = parseMetadata(metadata); 104 | 105 | if (metadata.isFolder()) { 106 | jMetadata.addProperty("is_root", metadata.isRoot()); 107 | } else { 108 | JsonArray chunks = new JsonArray(); 109 | 110 | for (String chunk : metadata.getChunks()) { 111 | JsonElement elem = new JsonPrimitive(chunk); 112 | chunks.add(elem); 113 | } 114 | 115 | jMetadata.add("chunks", chunks); 116 | } 117 | 118 | return jMetadata; 119 | } 120 | 121 | protected JsonObject parseMetadata(ItemMetadata metadata) { 122 | JsonObject jMetadata = new JsonObject(); 123 | 124 | if (metadata == null) { 125 | return jMetadata; 126 | } 127 | 128 | jMetadata.addProperty("id", metadata.getId()); 129 | jMetadata.addProperty("parent_id", metadata.getParentId()); 130 | jMetadata.addProperty("filename", metadata.getFilename()); 131 | jMetadata.addProperty("is_folder", metadata.isFolder()); 132 | jMetadata.addProperty("status", metadata.getStatus()); 133 | 134 | if (metadata.getModifiedAt() != null) { 135 | jMetadata.addProperty("modified_at", metadata.getModifiedAt().toString()); 136 | } 137 | 138 | jMetadata.addProperty("version", metadata.getVersion()); 139 | jMetadata.addProperty("checksum", metadata.getChecksum()); 140 | jMetadata.addProperty("size", metadata.getSize()); 141 | jMetadata.addProperty("mimetype", metadata.getMimetype()); 142 | 143 | return jMetadata; 144 | } 145 | 146 | protected JsonObject parseUser(User user) { 147 | JsonObject jUser = new JsonObject(); 148 | 149 | if (user == null) { 150 | return jUser; 151 | } 152 | 153 | jUser.addProperty("name", user.getName()); 154 | jUser.addProperty("email", user.getEmail()); 155 | 156 | return jUser; 157 | 158 | } 159 | 160 | protected JsonObject parseUserWorkspace(UserWorkspace userWorkspace) { 161 | 162 | if (userWorkspace == null) { 163 | return new JsonObject(); 164 | } 165 | 166 | JsonObject jUser = parseUser(userWorkspace.getUser()); 167 | jUser.addProperty("is_owner", userWorkspace.isOwner()); 168 | jUser.addProperty("joined_at", userWorkspace.getJoinedAt().toString()); 169 | 170 | return jUser; 171 | 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIRestoreMetadata.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.stacksync.commons.models.CommitInfo; 4 | import com.stacksync.commons.models.ItemMetadata; 5 | 6 | public class APIRestoreMetadata extends APIResponse { 7 | 8 | public APIRestoreMetadata(ItemMetadata item, Boolean success, int error, String description) { 9 | super(); 10 | this.success = success; 11 | this.errorCode = error; 12 | this.description = description; 13 | this.item = new CommitInfo(item.getVersion(), 14 | success, item); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIShareFolderResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.JsonObject; 5 | import com.stacksync.commons.models.User; 6 | import com.stacksync.commons.models.Workspace; 7 | 8 | public class APIShareFolderResponse extends APIResponse { 9 | 10 | private Workspace workspace; 11 | 12 | public APIShareFolderResponse(Workspace workspace, Boolean success, int error, String description) { 13 | super(); 14 | 15 | this.success = success; 16 | this.workspace = workspace; 17 | this.description = description; 18 | this.errorCode = error; 19 | } 20 | 21 | public Workspace getWorkspace() { 22 | return workspace; 23 | } 24 | 25 | @Override 26 | public String toString() { 27 | JsonObject jResponse = new JsonObject(); 28 | 29 | if (getSuccess()) { 30 | 31 | JsonArray sharedTo = new JsonArray(); 32 | 33 | for (User user : workspace.getUsers()) { 34 | JsonObject jUser = parseUser(user); 35 | sharedTo.add(jUser); 36 | } 37 | 38 | jResponse.add("shared_to", sharedTo); 39 | 40 | } else { 41 | jResponse.addProperty("error", getErrorCode()); 42 | jResponse.addProperty("description", getDescription()); 43 | } 44 | 45 | return jResponse.toString(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIUnshareFolderResponse.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import java.util.List; 4 | 5 | import com.google.gson.JsonArray; 6 | import com.google.gson.JsonObject; 7 | import com.stacksync.commons.models.User; 8 | import com.stacksync.commons.models.Workspace; 9 | 10 | public class APIUnshareFolderResponse extends APIResponse { 11 | private List usersToRemove; 12 | private Workspace workspace; 13 | private boolean isUnshared; 14 | 15 | public APIUnshareFolderResponse(Workspace workspace, List usersToRemove, boolean isUnshared, Boolean success, int error, String description) { 16 | super(); 17 | 18 | this.success = success; 19 | this.workspace = workspace; 20 | this.description = description; 21 | this.errorCode = error; 22 | this.usersToRemove = usersToRemove; 23 | this.isUnshared = isUnshared; 24 | } 25 | 26 | public Workspace getWorkspace() { 27 | return workspace; 28 | } 29 | 30 | public List getUsersToRemove() { 31 | return usersToRemove; 32 | } 33 | 34 | public boolean isUnshared() { 35 | return isUnshared; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | JsonObject jResponse = new JsonObject(); 41 | 42 | if (getSuccess()) { 43 | 44 | JsonArray sharedTo = new JsonArray(); 45 | 46 | for (User user : usersToRemove) { 47 | JsonObject jUser = parseUser(user); 48 | sharedTo.add(jUser); 49 | } 50 | 51 | jResponse.add("unshared_to", sharedTo); 52 | 53 | } else { 54 | jResponse.addProperty("error", getErrorCode()); 55 | jResponse.addProperty("description", getDescription()); 56 | } 57 | 58 | return jResponse.toString(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/messages/APIUserMetadata.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.messages; 2 | 3 | import com.stacksync.commons.models.User; 4 | 5 | public class APIUserMetadata extends APIResponse { 6 | 7 | private User user; 8 | 9 | public APIUserMetadata(User user, Boolean success, int error, String description) { 10 | super(); 11 | this.success = success; 12 | this.description = description; 13 | this.errorCode = error; 14 | this.user = user; 15 | } 16 | 17 | public User getUser() { 18 | return user; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/parser/IParser.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.parser; 2 | 3 | import com.stacksync.syncservice.rpc.messages.APIResponse; 4 | 5 | public interface IParser { 6 | public String createResponse(APIResponse m); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/rpc/parser/JSONParser.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.rpc.parser; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | import com.google.gson.JsonArray; 6 | import com.google.gson.JsonElement; 7 | import com.google.gson.JsonObject; 8 | import com.google.gson.JsonPrimitive; 9 | import com.stacksync.commons.models.ItemMetadata; 10 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 11 | import com.stacksync.syncservice.rpc.messages.APICreateFolderResponse; 12 | import com.stacksync.syncservice.rpc.messages.APIDeleteResponse; 13 | import com.stacksync.syncservice.rpc.messages.APIGetMetadata; 14 | import com.stacksync.syncservice.rpc.messages.APIGetVersions; 15 | import com.stacksync.syncservice.rpc.messages.APIResponse; 16 | import com.stacksync.syncservice.rpc.messages.APIRestoreMetadata; 17 | 18 | public class JSONParser implements IParser { 19 | 20 | private static final Logger logger = Logger.getLogger(JSONParser.class.getName()); 21 | 22 | public JSONParser() { } 23 | 24 | public String createResponse(APIResponse response) { 25 | JsonObject jResponse = null; 26 | String bResponse = ""; 27 | 28 | try { 29 | if (response instanceof APIGetMetadata) { 30 | jResponse = this.createGetMetadataResponse((APIGetMetadata) response); 31 | } else if (response instanceof APIGetVersions) { 32 | jResponse = this.createGetVersionsResponse((APIGetVersions) response); 33 | } else if (response instanceof APICommitResponse 34 | || response instanceof APIDeleteResponse 35 | || response instanceof APIRestoreMetadata 36 | || response instanceof APICreateFolderResponse) { 37 | jResponse = this.createGenericAPIResponse(response); 38 | } 39 | 40 | if (jResponse != null) { 41 | bResponse = jResponse.toString(); 42 | } 43 | 44 | } catch (Exception ex) { 45 | logger.error(ex.toString(), ex); 46 | } 47 | 48 | return bResponse; 49 | } 50 | 51 | private JsonObject createGetVersionsResponse(APIGetVersions response) { 52 | JsonObject jResponse = new JsonObject(); 53 | 54 | if (response.getSuccess()) { 55 | ItemMetadata metadata = response.getItemMetadata(); 56 | jResponse = parseObjectMetadataForAPI(metadata); 57 | 58 | if (metadata.getChildren() != null) { 59 | JsonArray contents = new JsonArray(); 60 | 61 | for (ItemMetadata entry : metadata.getChildren()) { 62 | JsonObject entryJson = parseObjectMetadataForAPI(entry); 63 | contents.add(entryJson); 64 | } 65 | 66 | jResponse.add("versions", contents); 67 | } 68 | } else { 69 | jResponse.addProperty("error", response.getErrorCode()); 70 | jResponse.addProperty("description", response.getDescription()); 71 | } 72 | 73 | return jResponse; 74 | } 75 | 76 | private JsonObject createGenericAPIResponse(APIResponse response) { 77 | JsonObject jResponse; 78 | 79 | if (!response.getSuccess()) { 80 | jResponse = new JsonObject(); 81 | jResponse.addProperty("description", response.getDescription()); 82 | jResponse.addProperty("error", response.getErrorCode()); 83 | } else { 84 | ItemMetadata file = response.getItem().getMetadata(); 85 | jResponse = this.parseItemMetadata(file); 86 | } 87 | 88 | return jResponse; 89 | } 90 | 91 | private JsonObject createGetMetadataResponse(APIGetMetadata response) { 92 | JsonObject jResponse = new JsonObject(); 93 | 94 | if (response.getSuccess()) { 95 | ItemMetadata metadata = response.getItemMetadata(); 96 | jResponse = parseObjectMetadataForAPI(metadata); 97 | 98 | if (metadata.getChildren() != null) { 99 | JsonArray contents = new JsonArray(); 100 | 101 | for (ItemMetadata entry : metadata.getChildren()) { 102 | JsonObject entryJson = parseObjectMetadataForAPI(entry); 103 | contents.add(entryJson); 104 | } 105 | 106 | jResponse.add("contents", contents); 107 | } 108 | } else { 109 | jResponse.addProperty("error", response.getErrorCode()); 110 | jResponse.addProperty("description", response.getDescription()); 111 | } 112 | 113 | return jResponse; 114 | } 115 | 116 | private JsonObject parseMetadata(ItemMetadata metadata) { 117 | JsonObject jMetadata = new JsonObject(); 118 | 119 | if (metadata == null) { 120 | return jMetadata; 121 | } 122 | 123 | jMetadata.addProperty("id", metadata.getId()); 124 | jMetadata.addProperty("parent_id", metadata.getParentId()); 125 | jMetadata.addProperty("filename", metadata.getFilename()); 126 | jMetadata.addProperty("is_folder", metadata.isFolder()); 127 | jMetadata.addProperty("status", metadata.getStatus()); 128 | 129 | if (metadata.getModifiedAt() != null) { 130 | jMetadata.addProperty("modified_at", metadata.getModifiedAt().toString()); 131 | } 132 | 133 | jMetadata.addProperty("version", metadata.getVersion()); 134 | jMetadata.addProperty("checksum", metadata.getChecksum()); 135 | jMetadata.addProperty("size", metadata.getSize()); 136 | jMetadata.addProperty("mimetype", metadata.getMimetype()); 137 | 138 | return jMetadata; 139 | } 140 | 141 | private JsonObject parseObjectMetadataForAPI(ItemMetadata metadata) { 142 | JsonObject jMetadata = parseMetadata(metadata); 143 | 144 | if (metadata.isFolder()) { 145 | jMetadata.addProperty("is_root", metadata.isRoot()); 146 | } else { 147 | JsonArray chunks = new JsonArray(); 148 | 149 | for (String chunk : metadata.getChunks()) { 150 | JsonElement elem = new JsonPrimitive(chunk); 151 | chunks.add(elem); 152 | } 153 | 154 | jMetadata.add("chunks", chunks); 155 | } 156 | 157 | return jMetadata; 158 | } 159 | 160 | private JsonObject parseItemMetadata(ItemMetadata metadata) { 161 | JsonObject jMetadata = parseMetadata(metadata); 162 | 163 | // if (metadata.getParentId() == null) { 164 | // jMetadata.addProperty("parent_file_id", ""); 165 | // } else { 166 | // jMetadata.addProperty("parent_file_id", metadata.getParentId()); 167 | // } 168 | // 169 | // if (metadata.getParentId() == null) { 170 | // jMetadata.addProperty("parent_file_version", ""); 171 | // } else { 172 | // jMetadata.addProperty("parent_file_version", metadata.getParentVersion()); 173 | // } 174 | 175 | // TODO: send only chunks when is a file 176 | if (!metadata.isFolder()) { 177 | JsonArray chunks = new JsonArray(); 178 | for (String chunk : metadata.getChunks()) { 179 | JsonElement elem = new JsonPrimitive(chunk); 180 | chunks.add(elem); 181 | } 182 | jMetadata.add("chunks", chunks); 183 | } 184 | 185 | return jMetadata; 186 | } 187 | 188 | } 189 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/StorageFactory.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage; 2 | 3 | import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; 4 | import com.stacksync.syncservice.storage.StorageManager.StorageType; 5 | 6 | public class StorageFactory { 7 | 8 | public static StorageManager getStorageManager(StorageType type) throws NoStorageManagerAvailable { 9 | 10 | if (type == StorageType.SWIFT) { 11 | return SwiftManager.getInstance(); 12 | } else if (type == StorageType.SWIFT_SSL) { 13 | return SwiftManagerHTTPS.getInstance(); 14 | } 15 | 16 | throw new NoStorageManagerAvailable(String.format("Storage type '%s' not found", type)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/StorageManager.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage; 2 | 3 | import com.stacksync.commons.models.User; 4 | import com.stacksync.commons.models.Workspace; 5 | 6 | public abstract class StorageManager { 7 | 8 | public enum StorageType { 9 | 10 | SWIFT, SWIFT_SSL, FTP 11 | } 12 | 13 | public abstract void login() throws Exception; 14 | 15 | public abstract void createNewWorkspace(Workspace workspace) throws Exception; 16 | 17 | public abstract void removeUserToWorkspace(User owner, User user, Workspace workspace) throws Exception; 18 | 19 | public abstract void grantUserToWorkspace(User owner, User user, Workspace workspace) throws Exception; 20 | 21 | public abstract void copyChunk(Workspace sourceWorkspace, Workspace destinationWorkspace, String chunkName) throws Exception; 22 | 23 | public abstract void deleteChunk(Workspace workspace, String chunkName) throws Exception; 24 | 25 | public abstract void deleteWorkspace(Workspace workspace) throws Exception; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/swift/AccessObject.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage.swift; 2 | 3 | import java.util.List; 4 | 5 | public class AccessObject { 6 | 7 | private TokenObject token; 8 | private List serviceCatalog; 9 | 10 | public TokenObject getToken() { 11 | return token; 12 | } 13 | public List getServiceCatalog() { 14 | return serviceCatalog; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/swift/EndpointObject.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage.swift; 2 | 3 | public class EndpointObject { 4 | 5 | private String adminURL; 6 | private String region; 7 | private String internalURL; 8 | private String id; 9 | private String publicURL; 10 | 11 | public String getAdminURL() { 12 | return adminURL; 13 | } 14 | public String getRegion() { 15 | return region; 16 | } 17 | public String getInternalURL() { 18 | return internalURL; 19 | } 20 | public String getId() { 21 | return id; 22 | } 23 | public String getPublicURL() { 24 | return publicURL; 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/swift/LoginResponseObject.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage.swift; 2 | 3 | public class LoginResponseObject { 4 | 5 | private AccessObject access; 6 | 7 | public AccessObject getAccess() { 8 | return access; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/swift/ServiceObject.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage.swift; 2 | 3 | import java.util.List; 4 | 5 | public class ServiceObject { 6 | 7 | private List endpoints; 8 | private String type; 9 | private String swift; 10 | 11 | public List getEndpoints() { 12 | return endpoints; 13 | } 14 | public String getType() { 15 | return type; 16 | } 17 | public String getSwift() { 18 | return swift; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/storage/swift/TokenObject.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.storage.swift; 2 | 3 | public class TokenObject { 4 | 5 | private String issued_at; 6 | private String expires; 7 | private String id; 8 | 9 | public String getIssuedAt() { 10 | return issued_at; 11 | } 12 | public String getExpires() { 13 | return expires; 14 | } 15 | public String getId() { 16 | return id; 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/stacksync/syncservice/util/CleanObjects.java: -------------------------------------------------------------------------------- 1 | /* 2 | * HOW TO USE: 3 | * - cleanUserObjects(userID): Delete ALL metadata from ALL workspaces 4 | * - cleanUserObjects(userID, workspaceID): Delete ALL metadata from 5 | * workspaceID 6 | */ 7 | 8 | package com.stacksync.syncservice.util; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class CleanObjects { 14 | 15 | //private RiakConnector rc; 16 | 17 | public CleanObjects(String ip, int port) throws Exception{ 18 | //this.rc = new RiakConnector(ip, port); 19 | } 20 | 21 | public void cleanUserObjects(String userID){ 22 | /* 23 | try { 24 | List workspaces = this.rc.getUserWorkspace(userID); 25 | for (String workspace : workspaces){ 26 | cleanUserObjects(userID, workspace); 27 | } 28 | } catch (Exception e){ 29 | System.out.println(e.toString()); 30 | } 31 | */ 32 | } 33 | 34 | public void cleanUserObjects(String userID, String workspace){ 35 | /* 36 | try { 37 | JSONObject objects = this.rc.getWorkspaceObjects(workspace); 38 | Iterator iterObjects = objects.keys(); 39 | 40 | while( iterObjects.hasNext() ){ 41 | String objectID = iterObjects.next(); 42 | JSONObject fileMetadata = objects.getJSONObject(objectID); 43 | int latestVersion = fileMetadata.getInt(Constants.KEY_VERSION); 44 | 45 | for (int i=1; i<=latestVersion; i++){ 46 | String key = workspace+":"+objectID+":"+i; 47 | this.rc.deleteObjectVersionResource(key); 48 | } 49 | } 50 | 51 | this.rc.putWorkspaceObjectResource(workspace, new JSONObject()); 52 | 53 | } catch (Exception e){ 54 | System.out.println(e.toString()); 55 | } 56 | */ 57 | } 58 | 59 | public static void showUsage(){ 60 | System.out.println("Usage:"); 61 | System.out.println("\t-u user_id (required)"); 62 | System.out.println("\t-i ip (required)"); 63 | System.out.println("\t-p port (required)"); 64 | System.out.println("\t-w workspace_id (optional)"); 65 | System.out.println("Example: CleanObjects -u 123 -i 127.0.0.1 -p 8087 -w a -w b"); 66 | } 67 | 68 | public static void main(String[] argv) throws Exception{ 69 | 70 | 71 | if ( argv.length < 2 || argv.length%2 != 0){ 72 | showUsage(); 73 | System.exit(1); 74 | } 75 | 76 | String userID = null; 77 | String ip = null; 78 | int port = -1; 79 | List workspaces = new ArrayList(); 80 | 81 | for ( int i=0; i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/resources/version.properties: -------------------------------------------------------------------------------- 1 | version=${project.version} -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/Constants.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark; 2 | 3 | import java.util.UUID; 4 | 5 | public class Constants { 6 | public static UUID USER = new UUID(1, 1); 7 | public static UUID WORKSPACE_ID = new UUID(1, 1); 8 | public static String REQUEST_ID = "Benchmark"; 9 | public static UUID DEVICE_ID = new UUID(1, 1); 10 | public static Integer XMLRPC_PORT = com.stacksync.syncservice.util.Constants.XMLRPC_PORT; 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/DBBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Random; 6 | import java.util.UUID; 7 | 8 | import com.stacksync.commons.models.Device; 9 | import com.stacksync.commons.models.Item; 10 | import com.stacksync.commons.models.User; 11 | import com.stacksync.commons.models.Workspace; 12 | import com.stacksync.syncservice.exceptions.dao.DAOException; 13 | import com.stacksync.syncservice.test.benchmark.db.DatabaseHelper; 14 | 15 | 16 | public class DBBenchmark extends Thread { 17 | 18 | private static final int LEVELS = 3; 19 | private static final int USERS = 30; 20 | 21 | private String name; 22 | private int numUser; 23 | private int fsDepth; 24 | private MetadataGenerator metadataGen; 25 | private DatabaseHelper dbHelper; 26 | 27 | 28 | public DBBenchmark(int numUser) throws Exception { 29 | super("TName" + numUser); 30 | 31 | this.name = "TName" + numUser; 32 | this.numUser = numUser; 33 | this.fsDepth = LEVELS; 34 | this.dbHelper = new DatabaseHelper(); 35 | this.metadataGen = new MetadataGenerator(); 36 | } 37 | 38 | public void fillDB(Workspace workspace, Device device) { 39 | int firstLevel = 0; 40 | 41 | try { 42 | this.createAndStoreMetadata(workspace, device, firstLevel, null); 43 | } catch (IllegalArgumentException e) { 44 | e.printStackTrace(); 45 | } catch (DAOException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | 50 | public void createAndStoreMetadata(Workspace workspace, Device device, int currentLevel, Item parent) 51 | throws IllegalArgumentException, DAOException { 52 | 53 | if (currentLevel >= this.fsDepth) { 54 | return; 55 | } 56 | 57 | List objectsLevel = metadataGen.generateLevel(workspace, device, parent); 58 | this.dbHelper.storeObjects(objectsLevel); 59 | 60 | for (Item object : objectsLevel) { 61 | if (object.isFolder()) { 62 | createAndStoreMetadata(workspace, device, currentLevel + 1, object); 63 | } 64 | } 65 | 66 | System.out.println("***** " + name + " --> Stored objects: " + objectsLevel.size() + " at level: " + currentLevel); 67 | } 68 | 69 | @Override 70 | public void run(){ 71 | Random randGenerator = new Random(); 72 | System.out.println("============================"); 73 | System.out.println("=========Thread " + name + "========="); 74 | System.out.println("============================"); 75 | System.out.println("============================"); 76 | 77 | System.out.println("Creating user: " + numUser); 78 | int randomUser = randGenerator.nextInt(); 79 | String name = "benchmark" + randomUser; 80 | String cloudId = name; 81 | 82 | try { 83 | User user = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L, 0L, 0L); 84 | dbHelper.addUser(user); 85 | 86 | Workspace workspace = new Workspace(null, 1, user, false, false); 87 | dbHelper.addWorkspace(user, workspace); 88 | 89 | String deviceName = name + "_device"; 90 | Device device = new Device(null, deviceName, user); 91 | dbHelper.addDevice(device); 92 | 93 | fillDB(workspace, device); 94 | 95 | System.out.println("User -> " + user); 96 | System.out.println("Workspace -> " + workspace); 97 | System.out.println("Device -> " + device); 98 | } catch (IllegalArgumentException e) { 99 | // TODO Auto-generated catch block 100 | e.printStackTrace(); 101 | } catch (DAOException e) { 102 | // TODO Auto-generated catch block 103 | e.printStackTrace(); 104 | } 105 | } 106 | 107 | 108 | 109 | public static void main(String[] args) { 110 | try { 111 | int numThreads = 1; 112 | List benchmarks = new ArrayList(); 113 | for (int numUser = 0; numUser < USERS; numUser+=numThreads) { 114 | 115 | for(int i=0; i generateLevel(Workspace workspace, Device device, Item parent) { 35 | int objectsLevel = randGenerator.nextInt(MAX_FILES_LEVEL); 36 | ArrayList objects = new ArrayList(); 37 | 38 | for (int i = 0; i < objectsLevel; i++) { 39 | Item currentObject; 40 | int folderValue = randGenerator.nextInt(totalPercentage); 41 | boolean folder = false; 42 | 43 | if (folderValue < folderPercentage) { 44 | folder = true; 45 | } 46 | 47 | currentObject = this.generateMetadata(workspace, device, parent, folder); 48 | objects.add(currentObject); 49 | } 50 | 51 | return objects; 52 | } 53 | 54 | private Item generateMetadata(Workspace workspace, Device device, Item parent, boolean folder) { 55 | long numVersions = randGenerator.nextInt(MAX_VERSIONS); 56 | if (numVersions == 0) { 57 | numVersions = 1; 58 | } 59 | 60 | int numChunks = randGenerator.nextInt(MAX_CHUNKS); 61 | if (numChunks == 0) { 62 | numChunks = 1; 63 | } 64 | 65 | Item item = new Item(); 66 | item.setWorkspace(workspace); 67 | item.setLatestVersion(numVersions); 68 | item.setParent(parent); 69 | item.setId((long) randGenerator.nextInt()); // If nextLong 70 | // fails! 71 | item.setFilename(randomString()); 72 | item.setMimetype("Document"); 73 | item.setIsFolder(folder); 74 | 75 | if (parent == null) { 76 | item.setClientParentFileVersion(null); 77 | } else { 78 | item.setClientParentFileVersion(parent.getLatestVersion()); 79 | } 80 | 81 | List versions = new ArrayList(); 82 | for (int i = 0; i < numVersions; i++) { 83 | ItemVersion version = new ItemVersion(); 84 | version.setItem(item); 85 | version.setDevice(device); 86 | version.setVersion(i + 1L); 87 | version.setModifiedAt(new Date()); 88 | version.setChecksum(randGenerator.nextLong()); 89 | 90 | if (i == 0) { 91 | version.setStatus("NEW"); 92 | } else { 93 | version.setStatus("CHANGED"); // TODO improve with random 94 | // (DELETED, RENA..) 95 | } 96 | 97 | version.setSize((long) randGenerator.nextInt(10000)); 98 | 99 | List chunks = new ArrayList(); 100 | if (!folder) { 101 | for (int j = 0; j < numChunks; j++) { 102 | Chunk chunk = new Chunk(); 103 | chunk.setClientChunkName(randomString()); 104 | chunks.add(chunk); 105 | } 106 | } 107 | version.setChunks(chunks); 108 | versions.add(version); 109 | } 110 | item.setVersions(versions); 111 | 112 | //System.out.println("Object Metadata -> " + object); 113 | return item; 114 | } 115 | 116 | protected String randomString() { 117 | return new BigInteger(130, this.randGenerator).toString(32); 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/db/DatabaseHelper.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.db; 2 | 3 | import java.sql.Connection; 4 | import java.util.List; 5 | import java.util.UUID; 6 | 7 | import com.stacksync.commons.models.Device; 8 | import com.stacksync.commons.models.Item; 9 | import com.stacksync.commons.models.ItemVersion; 10 | import com.stacksync.commons.models.User; 11 | import com.stacksync.commons.models.Workspace; 12 | import com.stacksync.syncservice.db.ConnectionPool; 13 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 14 | import com.stacksync.syncservice.db.DAOFactory; 15 | import com.stacksync.syncservice.db.DeviceDAO; 16 | import com.stacksync.syncservice.db.ItemDAO; 17 | import com.stacksync.syncservice.db.ItemVersionDAO; 18 | import com.stacksync.syncservice.db.UserDAO; 19 | import com.stacksync.syncservice.db.WorkspaceDAO; 20 | import com.stacksync.syncservice.exceptions.dao.DAOException; 21 | import com.stacksync.syncservice.util.Config; 22 | 23 | public class DatabaseHelper { 24 | private ConnectionPool pool; 25 | private Connection connection; 26 | private WorkspaceDAO workspaceDAO; 27 | private UserDAO userDao; 28 | private DeviceDAO deviceDao; 29 | private ItemDAO objectDao; 30 | private ItemVersionDAO oversionDao; 31 | 32 | public DatabaseHelper() throws Exception { 33 | Config.loadProperties(); 34 | Thread.sleep(100); 35 | 36 | String datasource = Config.getDatasource(); 37 | 38 | pool = ConnectionPoolFactory.getConnectionPool(datasource); 39 | connection = pool.getConnection(); 40 | 41 | DAOFactory factory = new DAOFactory(datasource); 42 | 43 | workspaceDAO = factory.getWorkspaceDao(connection); 44 | userDao = factory.getUserDao(connection); 45 | deviceDao = factory.getDeviceDAO(connection); 46 | objectDao = factory.getItemDAO(connection); 47 | oversionDao = factory.getItemVersionDAO(connection); 48 | } 49 | 50 | public void storeObjects(List objectsLevel) throws IllegalArgumentException, DAOException { 51 | 52 | long numChunk = 0, totalTimeChunk = 0; 53 | long numVersion = 0, totalTimeVersion = 0; 54 | long numObject = 0, totalTimeObject = 0; 55 | 56 | long startTotal = System.currentTimeMillis(); 57 | for (Item object : objectsLevel) { 58 | // System.out.println("DatabaseHelper -- Put Object -> " + object); 59 | long startObjectTotal = System.currentTimeMillis(); 60 | 61 | objectDao.put(object); 62 | for (ItemVersion version : object.getVersions()) { 63 | 64 | long startVersionTotal = System.currentTimeMillis(); 65 | // System.out.println("DatabaseHelper -- Put Version -> " + 66 | // version); 67 | oversionDao.add(version); 68 | 69 | long startChunkTotal = System.currentTimeMillis(); 70 | 71 | if (!version.getChunks().isEmpty()) { 72 | oversionDao.insertChunks(version.getChunks(), version.getId()); 73 | } 74 | 75 | totalTimeChunk += System.currentTimeMillis() - startChunkTotal; 76 | 77 | totalTimeVersion += System.currentTimeMillis() - startVersionTotal; 78 | // System.out.println("---- Total Version time --> " + 79 | // totalVersionTime + " ms"); 80 | numVersion++; 81 | } 82 | 83 | totalTimeObject += System.currentTimeMillis() - startObjectTotal; 84 | numObject++; 85 | } 86 | 87 | if (numChunk > 0) { 88 | System.out.println("-------- AVG avg Chunk(" + numChunk + ") time --> " + (totalTimeChunk / numChunk) + " ms"); 89 | } 90 | 91 | if (numVersion > 0) { 92 | System.out.println("---- AVG Version(" + numVersion + ") time --> " + (totalTimeVersion / numVersion) + " ms"); 93 | } 94 | 95 | if (numObject > 0) { 96 | System.out.println("AVG Object(" + numObject + ") time --> " + (totalTimeObject / numObject) + " ms"); 97 | } 98 | 99 | long totalTime = System.currentTimeMillis() - startTotal; 100 | 101 | System.out.println("Total level time --> " + totalTime + " ms"); 102 | 103 | } 104 | 105 | public void addUser(User user) throws IllegalArgumentException, DAOException { 106 | userDao.add(user); 107 | } 108 | 109 | public void addWorkspace(User user, Workspace workspace) throws IllegalArgumentException, DAOException { 110 | workspaceDAO.add(workspace); 111 | workspaceDAO.addUser(user, workspace); 112 | } 113 | 114 | public void addDevice(Device device) throws IllegalArgumentException, DAOException { 115 | deviceDao.add(device); 116 | } 117 | 118 | public void deleteUser(UUID id) throws DAOException { 119 | userDao.delete(id); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/normal/CommonFunctions.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.normal; 2 | 3 | import java.util.Date; 4 | import java.util.Random; 5 | import java.util.UUID; 6 | 7 | import com.google.gson.JsonArray; 8 | import com.google.gson.JsonElement; 9 | import com.google.gson.JsonObject; 10 | import com.google.gson.JsonPrimitive; 11 | 12 | public class CommonFunctions { 13 | 14 | public class ParentRoot { 15 | public String parentRootId; 16 | public Long fileVersion; 17 | public Long fileId; 18 | 19 | public ParentRoot(String parentRootId, Long fileVersion, Long fileId) { 20 | this.parentRootId = parentRootId; 21 | this.fileVersion = fileVersion; 22 | this.fileId = fileId; 23 | } 24 | } 25 | 26 | private static JsonArray generateChunks(int size) { 27 | JsonArray jArray = new JsonArray(); 28 | RandomString strRandom = new RandomString(20); 29 | 30 | for (int i = 0; i < size; i++) { 31 | JsonElement elem = new JsonPrimitive(strRandom.nextString()); 32 | jArray.add(elem); 33 | } 34 | 35 | return jArray; 36 | } 37 | 38 | private static JsonArray generateObjectsLevel(int numObjects, UUID deviceId, ParentRoot parentRoot) { 39 | JsonArray arrayObjects = new JsonArray(); 40 | 41 | Random random = new Random(); 42 | RandomString strRandom = new RandomString(10); 43 | for (int i = 0; i < numObjects; i++) { 44 | JsonObject file = new JsonObject(); 45 | 46 | file.addProperty("file_id", random.nextLong()); 47 | file.addProperty("version", new Long(1)); 48 | 49 | if (parentRoot != null) { 50 | file.addProperty("parent_file_version", parentRoot.fileVersion); 51 | file.addProperty("parent_file_id", parentRoot.fileId); 52 | } else { 53 | file.addProperty("parent_file_version", ""); 54 | file.addProperty("parent_file_id", ""); 55 | } 56 | 57 | Date date = new Date(); 58 | file.addProperty("updated", date.getTime()); 59 | 60 | file.addProperty("status", "NEW"); 61 | file.addProperty("lastModified", date.getTime()); 62 | 63 | file.addProperty("checksum", random.nextLong()); 64 | file.addProperty("clientName", deviceId.toString()); 65 | 66 | file.addProperty("fileSize", random.nextLong()); 67 | 68 | file.addProperty("folder", 0); 69 | file.addProperty("name", strRandom.nextString()); 70 | 71 | file.addProperty("path", strRandom.nextString()); 72 | 73 | file.addProperty("mimetype", "Text"); 74 | file.add("chunks", generateChunks(10)); 75 | 76 | arrayObjects.add(file); 77 | } 78 | 79 | return arrayObjects; 80 | } 81 | 82 | public static String generateObjects(int numObjects, UUID deviceId) { 83 | return CommonFunctions.generateObjectsLevel(numObjects, deviceId, null).toString(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/normal/RandomString.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.normal; 2 | 3 | import java.util.Random; 4 | 5 | public class RandomString { 6 | 7 | private static final char[] symbols = new char[36]; 8 | 9 | static { 10 | for (int idx = 0; idx < 10; ++idx) 11 | symbols[idx] = (char) ('0' + idx); 12 | for (int idx = 10; idx < 36; ++idx) 13 | symbols[idx] = (char) ('a' + idx - 10); 14 | } 15 | 16 | private final Random random = new Random(); 17 | 18 | private final char[] buf; 19 | 20 | public RandomString(int length) { 21 | if (length < 1) 22 | throw new IllegalArgumentException("length < 1: " + length); 23 | buf = new char[length]; 24 | } 25 | 26 | public String nextString() { 27 | for (int idx = 0; idx < buf.length; ++idx) 28 | buf[idx] = symbols[random.nextInt(symbols.length)]; 29 | return new String(buf); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/normal/TestCommit.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.normal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import com.google.gson.JsonArray; 8 | import com.google.gson.JsonObject; 9 | import com.google.gson.JsonParser; 10 | import com.stacksync.commons.models.Device; 11 | import com.stacksync.commons.models.ItemMetadata; 12 | import com.stacksync.commons.models.User; 13 | import com.stacksync.commons.models.Workspace; 14 | import com.stacksync.syncservice.db.ConnectionPool; 15 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 16 | import com.stacksync.syncservice.handler.Handler; 17 | import com.stacksync.syncservice.handler.SQLSyncHandler; 18 | import com.stacksync.syncservice.test.benchmark.Constants; 19 | import com.stacksync.syncservice.util.Config; 20 | 21 | public class TestCommit { 22 | 23 | public static List getObjectMetadata(JsonArray allFiles) { 24 | List metadataList = new ArrayList(); 25 | 26 | for (int i = 0; i < allFiles.size(); i++) { 27 | JsonObject file = allFiles.get(i).getAsJsonObject(); 28 | 29 | long fileId = file.get("file_id").getAsLong(); 30 | long version = file.get("version").getAsLong(); 31 | 32 | Long parentFileVersion = null; 33 | try { 34 | parentFileVersion = file.get("parent_file_version").getAsLong(); 35 | } catch (Exception ex) { 36 | // ex.printStackTrace(); 37 | } 38 | 39 | Long parentFileId = null; 40 | try { 41 | parentFileId = file.get("parent_file_id").getAsLong(); 42 | } catch (Exception ex) { 43 | // ex.printStackTrace(); 44 | } 45 | 46 | Date updated = new Date(file.get("updated").getAsLong()); 47 | String status = file.get("status").getAsString(); 48 | Date lastModified = new Date(file.get("lastModified").getAsLong()); 49 | long checksum = file.get("checksum").getAsLong(); 50 | long fileSize = file.get("fileSize").getAsLong(); 51 | 52 | int folderInt = file.get("folder").getAsInt(); 53 | boolean folder = folderInt == 0 ? false : true; 54 | 55 | String name = file.get("name").getAsString(); 56 | String mimetype = file.get("mimetype").getAsString(); 57 | JsonArray jChunks = file.get("chunks").getAsJsonArray(); // more 58 | // optimal 59 | List chunks = new ArrayList(); 60 | for (int j = 0; j < jChunks.size(); j++) { 61 | chunks.add(jChunks.get(j).getAsString()); 62 | } 63 | 64 | ItemMetadata object = new ItemMetadata(fileId, version, Constants.DEVICE_ID, parentFileId, parentFileVersion, status, lastModified, 65 | checksum, fileSize, folder, name, mimetype, chunks); 66 | 67 | metadataList.add(object); 68 | } 69 | 70 | return metadataList; 71 | } 72 | 73 | public static void main(String[] args) throws Exception { 74 | Config.loadProperties(); 75 | 76 | String datasource = Config.getDatasource(); 77 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 78 | Handler handler = new SQLSyncHandler(pool); 79 | 80 | String metadata = CommonFunctions.generateObjects(1, Constants.DEVICE_ID); 81 | long startTotal = System.currentTimeMillis(); 82 | 83 | JsonArray rawObjects = new JsonParser().parse(metadata).getAsJsonArray(); 84 | List objects = getObjectMetadata(rawObjects); 85 | 86 | User user = new User(); 87 | user.setId(Constants.USER); 88 | Device device = new Device( Constants.DEVICE_ID); 89 | Workspace workspace = new Workspace(Constants.WORKSPACE_ID); 90 | 91 | handler.doCommit(user, workspace, device, objects); 92 | 93 | long totalTime = System.currentTimeMillis() - startTotal; 94 | // System.out.println("Objects -> " + ((GetChangesResponseMessage) 95 | // response).getMetadata().size()); 96 | System.out.println("Total level time --> " + totalTime + " ms"); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/normal/TestGetChanges.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.normal; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.util.List; 7 | import java.util.zip.GZIPInputStream; 8 | import java.util.zip.GZIPOutputStream; 9 | 10 | import omq.common.util.Serializers.GsonImp; 11 | import omq.common.util.Serializers.ISerializer; 12 | import omq.common.util.Serializers.JavaImp; 13 | import omq.common.util.Serializers.KryoImp; 14 | import omq.exception.SerializerException; 15 | 16 | import com.stacksync.commons.models.ItemMetadata; 17 | import com.stacksync.commons.models.User; 18 | import com.stacksync.commons.models.Workspace; 19 | import com.stacksync.syncservice.test.benchmark.Constants; 20 | import com.stacksync.syncservice.db.ConnectionPool; 21 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 22 | import com.stacksync.syncservice.handler.Handler; 23 | import com.stacksync.syncservice.handler.SQLSyncHandler; 24 | import com.stacksync.syncservice.util.Config; 25 | 26 | public class TestGetChanges { 27 | 28 | public static byte[] zip(byte[] b) throws IOException { 29 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 30 | 31 | GZIPOutputStream zos = new GZIPOutputStream(baos); 32 | zos.write(b); 33 | zos.close(); 34 | 35 | return baos.toByteArray(); 36 | } 37 | 38 | public static byte[] unzip(byte[] b) throws IOException { 39 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 40 | ByteArrayInputStream bais = new ByteArrayInputStream(b); 41 | 42 | GZIPInputStream zis = new GZIPInputStream(bais); 43 | byte[] tmpBuffer = new byte[256]; 44 | int n; 45 | while ((n = zis.read(tmpBuffer)) >= 0) { 46 | baos.write(tmpBuffer, 0, n); 47 | } 48 | zis.close(); 49 | 50 | return baos.toByteArray(); 51 | } 52 | 53 | public static Boolean compareByteArray(byte[] array1, byte[] array2) { 54 | 55 | if (array1.length != array2.length) { 56 | return false; 57 | } 58 | 59 | for (int i = 0; i < array1.length; i++) { 60 | if (array1[i] != array2[i]) { 61 | return false; 62 | } 63 | } 64 | 65 | return true; 66 | } 67 | 68 | private static void printSize(ISerializer serializer, List list) throws IOException { 69 | try { 70 | long start = System.currentTimeMillis(); 71 | byte[] bytes = serializer.serialize(list); 72 | long total = System.currentTimeMillis() - start; 73 | 74 | byte[] compressed = zip(bytes); 75 | System.out.println(serializer.getClass().getName() + " -- Tiempo: " + total + " ms || Tama�o: " + bytes.length + " Bytes"); 76 | 77 | byte[] uncompressed = unzip(compressed); 78 | System.out.println("Compressed: " + compressed.length + " Bytes || UnCompressed: " + uncompressed.length + " Bytes" + " || Compare: " 79 | + compareByteArray(uncompressed, bytes)); 80 | 81 | } catch (SerializerException e) { 82 | e.printStackTrace(); 83 | } 84 | } 85 | 86 | public static void main(String[] args) throws Exception { 87 | /*Config.loadProperties(); 88 | 89 | String datasource = Config.getDatasource(); 90 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 91 | Handler handler = new SQLSyncHandler(pool); 92 | 93 | long startTotal = System.currentTimeMillis(); 94 | // [User:AUTH_e26e8353dbd043ae857ad6962e02f5cc, 95 | // Request:gguerrero201305161637-1368778961517, Workspace: 96 | // RemoteWorkspace[id=benchmark-93539494/, latestRevision=1, path=/]] 97 | // GetChangesMessage getChangesRequest = new 98 | // GetChangesMessage("AUTH_e26e8353dbd043ae857ad6962e02f5cc", 99 | // Message.GET_CHANGES, Constants.REQUESTID, "benchmark-93539494/", ""); 100 | 101 | User user = new User(); 102 | user.setId(Constants.USER); 103 | Workspace workspace = new Workspace(Constants.WORKSPACE_ID); 104 | 105 | List listFiles = handler.doGetChanges(user, workspace); 106 | 107 | System.out.println("Objects -> " + listFiles.size()); 108 | int countChk = 0; 109 | for (ItemMetadata obj : listFiles) { 110 | countChk += obj.getChunks().size(); 111 | } 112 | System.out.println("Chunks -> " + countChk); 113 | 114 | printSize(new JavaImp(), listFiles); 115 | printSize(new GsonImp(), listFiles); 116 | // printSize(new JsonImp(), listFiles); 117 | printSize(new KryoImp(), listFiles); 118 | // printSize(new XmlImp(), listFiles); 119 | // printSize(new YamlImp(), listFiles); 120 | 121 | long totalTime = System.currentTimeMillis() - startTotal; 122 | // System.out.println("Objects -> " + ((GetChangesResponseMessage) 123 | // response).getMetadata().size()); 124 | System.out.println("Total level time --> " + totalTime + " ms");*/ 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/normal/TestGetWorkspaces.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.normal; 2 | 3 | import com.stacksync.commons.models.User; 4 | import com.stacksync.syncservice.db.ConnectionPool; 5 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 6 | import com.stacksync.syncservice.handler.Handler; 7 | import com.stacksync.syncservice.handler.SQLSyncHandler; 8 | import com.stacksync.syncservice.test.benchmark.Constants; 9 | import com.stacksync.syncservice.util.Config; 10 | 11 | public class TestGetWorkspaces { 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | Config.loadProperties(); 16 | String datasource = Config.getDatasource(); 17 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 18 | Handler handler = new SQLSyncHandler(pool); 19 | 20 | long startTotal = System.currentTimeMillis(); 21 | 22 | /*User user = new User(Constants.USER); 23 | 24 | handler.doGetWorkspaces(user);*/ 25 | 26 | /* 27 | * List list = new ArrayList(); for 28 | * (Workspace w : response.getWorkspaces()) { try { RemoteWorkspace 29 | * workspace = new RemoteWorkspaceImp(w); list.add(workspace); } catch 30 | * (Exception e) { // TODO Auto-generated catch block 31 | * e.printStackTrace(); } } 32 | */ 33 | 34 | long totalTime = System.currentTimeMillis() - startTotal; 35 | // System.out.println("Result -> " + list); 36 | System.out.println("Total level time --> " + totalTime + " ms"); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/omq/RabbitConfig.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.omq; 2 | 3 | import java.util.Properties; 4 | 5 | import omq.common.util.ParameterQueue; 6 | 7 | public class RabbitConfig { 8 | 9 | public static Properties getProperties() { 10 | Properties env = new Properties(); 11 | env.setProperty(ParameterQueue.USER_NAME, "guest"); 12 | env.setProperty(ParameterQueue.USER_PASS, "guest"); 13 | 14 | // Get host info of rabbimq (where it is) 15 | env.setProperty(ParameterQueue.RABBIT_HOST, "10.30.239.228"); 16 | env.setProperty(ParameterQueue.RABBIT_PORT, "5672"); 17 | 18 | // Get info about the queue & the exchange where the RemoteListener will 19 | // listen to. 20 | env.setProperty(ParameterQueue.RPC_EXCHANGE, "rpc_global_exchange"); 21 | 22 | // Set info about the queue & the exchange where the ResponseListener 23 | // will listen to. 24 | env.setProperty(ParameterQueue.RPC_REPLY_QUEUE, "reply_gguerrero201305141718"); 25 | 26 | return env; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/omq/TestCommit.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.omq; 2 | 3 | import java.util.Properties; 4 | 5 | import omq.common.broker.Broker; 6 | 7 | import com.stacksync.commons.models.Workspace; 8 | import com.stacksync.commons.omq.ISyncService; 9 | import com.stacksync.syncservice.db.ConnectionPool; 10 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 11 | import com.stacksync.syncservice.db.DAOFactory; 12 | import com.stacksync.syncservice.db.WorkspaceDAO; 13 | import com.stacksync.syncservice.test.benchmark.Constants; 14 | import com.stacksync.syncservice.test.benchmark.normal.CommonFunctions; 15 | import com.stacksync.syncservice.util.Config; 16 | 17 | public class TestCommit { 18 | 19 | public static void main(String[] args) throws Exception { 20 | Config.loadProperties(); 21 | 22 | String datasource = Config.getDatasource(); 23 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 24 | 25 | Properties env = RabbitConfig.getProperties(); 26 | 27 | Broker broker = new Broker(env); 28 | broker.lookup(ISyncService.class.getSimpleName(), ISyncService.class); 29 | 30 | CommonFunctions.generateObjects(1, Constants.DEVICE_ID); 31 | 32 | DAOFactory factory = new DAOFactory(datasource); 33 | WorkspaceDAO workspaceDao = factory.getWorkspaceDao(pool.getConnection()); 34 | 35 | Workspace workspace = workspaceDao.getById(Constants.WORKSPACE_ID); 36 | 37 | long startTotal = System.currentTimeMillis(); 38 | // server.commit(Constants.USER, Constants.REQUESTID, rWorkspace, 39 | // Constants.DEVICENAME, metadata); 40 | 41 | long totalTime = System.currentTimeMillis() - startTotal; 42 | System.out.println("Total level time --> " + totalTime + " ms"); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/omq/TestGetChanges.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.omq; 2 | 3 | import java.util.List; 4 | import java.util.Properties; 5 | 6 | import omq.common.broker.Broker; 7 | import com.stacksync.commons.models.ItemMetadata; 8 | import com.stacksync.commons.omq.ISyncService; 9 | import com.stacksync.commons.requests.GetChangesRequest; 10 | import com.stacksync.syncservice.test.benchmark.Constants; 11 | import com.stacksync.syncservice.util.Config; 12 | 13 | public class TestGetChanges { 14 | 15 | public static void main(String[] args) throws Exception { 16 | Config.loadProperties(); 17 | 18 | Properties env = RabbitConfig.getProperties(); 19 | 20 | Broker broker = new Broker(env); 21 | ISyncService server = broker.lookup(ISyncService.class.getSimpleName(), ISyncService.class); 22 | 23 | long startTotal = System.currentTimeMillis(); 24 | 25 | GetChangesRequest request = new GetChangesRequest(Constants.USER, Constants.WORKSPACE_ID); 26 | 27 | List response = server.getChanges(request); 28 | 29 | System.out.println("Result objects -> " + response.size()); 30 | long totalTime = System.currentTimeMillis() - startTotal; 31 | System.out.println("Total level time --> " + totalTime + " ms"); 32 | 33 | System.exit(0); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/benchmark/omq/TestGetWorkspaces.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.benchmark.omq; 2 | 3 | import java.util.List; 4 | import java.util.Properties; 5 | 6 | import omq.common.broker.Broker; 7 | 8 | import com.stacksync.commons.models.Workspace; 9 | import com.stacksync.commons.omq.ISyncService; 10 | import com.stacksync.commons.requests.GetWorkspacesRequest; 11 | import com.stacksync.syncservice.test.benchmark.Constants; 12 | 13 | public class TestGetWorkspaces { 14 | 15 | public static void main(String[] args) throws Exception { 16 | Properties env = RabbitConfig.getProperties(); 17 | 18 | Broker broker = new Broker(env); 19 | ISyncService server = broker.lookup(ISyncService.class.getSimpleName(), ISyncService.class); 20 | 21 | long startTotal = System.currentTimeMillis(); 22 | GetWorkspacesRequest request = new GetWorkspacesRequest(Constants.USER); 23 | List workspaces = server.getWorkspaces(request); 24 | 25 | System.out.println("Result -> " + workspaces); 26 | long totalTime = System.currentTimeMillis() - startTotal; 27 | System.out.println("Total level time --> " + totalTime + " ms"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/CreateFileTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.Date; 7 | import java.util.Random; 8 | import java.util.UUID; 9 | 10 | import org.junit.BeforeClass; 11 | import org.junit.Test; 12 | 13 | import com.stacksync.commons.models.ItemMetadata; 14 | import com.stacksync.commons.models.User; 15 | import com.stacksync.commons.models.Workspace; 16 | import com.stacksync.syncservice.db.ConnectionPool; 17 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 18 | import com.stacksync.syncservice.db.DAOFactory; 19 | import com.stacksync.syncservice.db.UserDAO; 20 | import com.stacksync.syncservice.db.WorkspaceDAO; 21 | import com.stacksync.syncservice.handler.APIHandler; 22 | import com.stacksync.syncservice.handler.SQLAPIHandler; 23 | import com.stacksync.syncservice.handler.Handler.Status; 24 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 25 | import com.stacksync.syncservice.util.Config; 26 | import com.stacksync.syncservice.util.Constants; 27 | 28 | public class CreateFileTest { 29 | 30 | private static APIHandler handler; 31 | private static WorkspaceDAO workspaceDAO; 32 | private static UserDAO userDao; 33 | private static User user1; 34 | private static User user2; 35 | 36 | @BeforeClass 37 | public static void initializeData() throws Exception { 38 | 39 | Config.loadProperties(); 40 | 41 | String datasource = Config.getDatasource(); 42 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 43 | 44 | handler = new SQLAPIHandler(pool); 45 | DAOFactory factory = new DAOFactory(datasource); 46 | 47 | Connection connection = pool.getConnection(); 48 | 49 | 50 | workspaceDAO = factory.getWorkspaceDao(connection); 51 | userDao = factory.getUserDao(connection); 52 | 53 | user1 = new User(UUID.fromString("225130d4-c817-4df0-b4e2-13271b494ae5"), "tester_2", "tester_2", "AUTH_5e446d39e4294b57831da7ce3dd0d2c2", "test@stacksync.org", 100000L,0L, 0L); 54 | 55 | 56 | /* 57 | userDao.add(user1); 58 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 59 | workspaceDAO.add(workspace1); 60 | 61 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 62 | 63 | userDao.add(user2); 64 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 65 | workspaceDAO.add(workspace2); 66 | */ 67 | } 68 | 69 | @Test 70 | public void createNewFile() throws Exception { 71 | 72 | ItemMetadata file = new ItemMetadata(); 73 | file.setFilename("holaad8882.txt"); 74 | file.setParentId(null); 75 | file.setTempId(new Random().nextLong()); 76 | file.setIsFolder(false); 77 | file.setVersion(1L); 78 | file.setDeviceId(Constants.API_DEVICE_ID); 79 | file.setMimetype("image/jpeg"); 80 | file.setChecksum(0000000000L); 81 | file.setSize(99999L); 82 | file.setStatus(Status.NEW.toString()); 83 | file.setModifiedAt(new Date()); 84 | file.setChunks(Arrays.asList("11111", "22222", "333333")); 85 | 86 | APICommitResponse response = handler.createFile(user1, file); 87 | System.out.println(response.toString()); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/GetMetadataTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | 5 | import org.junit.AfterClass; 6 | import org.junit.BeforeClass; 7 | import org.junit.Test; 8 | 9 | import com.stacksync.syncservice.db.ConnectionPool; 10 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 11 | import com.stacksync.syncservice.db.DAOFactory; 12 | import com.stacksync.syncservice.db.UserDAO; 13 | import com.stacksync.syncservice.exceptions.dao.DAOException; 14 | import com.stacksync.syncservice.rpc.messages.APIGetMetadata; 15 | import com.stacksync.syncservice.rpc.parser.IParser; 16 | import com.stacksync.syncservice.rpc.parser.JSONParser; 17 | import com.stacksync.syncservice.util.Config; 18 | 19 | public class GetMetadataTest { 20 | 21 | private static IParser reader; 22 | private static UserDAO userDao; 23 | 24 | @BeforeClass 25 | public static void initializeData() { 26 | 27 | try { 28 | Config.loadProperties(); 29 | reader = new JSONParser(); 30 | 31 | String datasource = Config.getDatasource(); 32 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 33 | 34 | DAOFactory factory = new DAOFactory(datasource); 35 | 36 | Connection connection = pool.getConnection(); 37 | 38 | userDao = factory.getUserDao(connection); 39 | 40 | /* 41 | * UNCOMMENT TO INITIALIZE DATABASE (SLOW) 42 | * 43 | * DBBenchmark benchmark; int levels = 2; try { benchmark = new 44 | * DBBenchmark(levels); benchmark.fillDB(); } catch (Exception e) { 45 | * e.printStackTrace(); } 46 | */ 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | @AfterClass 53 | public static void cleanData() throws DAOException { 54 | //userDao.delete("bb"); 55 | } 56 | 57 | @Test 58 | public void getMetadataByCorrectFileId() throws DAOException { 59 | 60 | /* 61 | * String query = "{ " + "'user': 'bb', " + "'type': 'get_metadata'," + 62 | * "'fileId': '538757639', " + "'list': 'true', " + 63 | * "'include_deleted': 'false', " + "'version': '1' " + "}"; 64 | * 65 | * byte[] queryByte = query.getBytes(); 66 | * 67 | * GetMetadataMessage msg = (GetMetadataMessage) 68 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 69 | * handler.doGetMetadata(msg); 70 | * 71 | * assertTrue(response.getSucced()); 72 | * 73 | * printResponse(response); 74 | */ 75 | } 76 | 77 | @Test 78 | public void getMetadataByCorrectFileIdWithChunks() throws DAOException { 79 | 80 | /* 81 | * String query = "{ " + "'user': 'bb', " + "'type': 'get_metadata'," + 82 | * "'fileId': '538757639', " + "'list': 'true', " + 83 | * "'include_deleted': 'false', " + "'include_chunks': 'true' " + "}"; 84 | * 85 | * byte[] queryByte = query.getBytes(); 86 | * 87 | * GetMetadataMessage msg = (GetMetadataMessage) 88 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 89 | * handler.doGetMetadata(msg); 90 | * 91 | * assertTrue(response.getSucced()); 92 | * 93 | * printResponse(response); 94 | */ 95 | } 96 | 97 | @Test 98 | public void getMetadataByIncorrectFileId() throws DAOException { 99 | 100 | /* 101 | * String query = "{ " + "'user': 'bb', " + "'type': 'get_metadata'," + 102 | * "'fileId': '111111', " + "'list': 'true', " + 103 | * "'include_deleted': 'false', " + "'version': '1' " + "}"; 104 | * 105 | * byte[] queryByte = query.getBytes(); 106 | * 107 | * GetMetadataMessage msg = (GetMetadataMessage) 108 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 109 | * handler.doGetMetadata(msg); 110 | * 111 | * assertTrue(!response.getSucced() && response.getErrorCode() == 404); 112 | * 113 | * printResponse(response); 114 | */ 115 | } 116 | 117 | @Test 118 | public void getMetadataByCorrectFileIdIncorrectVersion() throws DAOException { 119 | 120 | /* 121 | * String query = "{ " + "'user': 'bb', " + "'type': 'get_metadata'," + 122 | * "'fileId': '538757639', " + "'list': 'true', " + 123 | * "'include_deleted': 'false', " + "'version': '1111' " + "}"; 124 | * 125 | * byte[] queryByte = query.getBytes(); 126 | * 127 | * GetMetadataMessage msg = (GetMetadataMessage) 128 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 129 | * handler.doGetMetadata(msg); 130 | * 131 | * assertTrue(!response.getSucced() && response.getErrorCode() == 404); 132 | * 133 | * printResponse(response); 134 | */ 135 | } 136 | 137 | @Test 138 | public void getMetadataByFileIdUserNotAuthorized() throws DAOException { 139 | 140 | /* 141 | * String query = "{ " + "'user': 'asd', " + "'type': 'get_metadata'," + 142 | * "'fileId': '538757639', " + "'list': 'true', " + 143 | * "'include_deleted': 'false', " + "'version': '1' " + "}"; 144 | * 145 | * byte[] queryByte = query.getBytes(); 146 | * 147 | * GetMetadataMessage msg = (GetMetadataMessage) 148 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 149 | * handler.doGetMetadata(msg); 150 | * 151 | * assertTrue(!response.getSucced() && response.getErrorCode() == 152 | * DAOError.USER_NOT_AUTHORIZED.getCode()); 153 | * 154 | * printResponse(response); 155 | */ 156 | } 157 | 158 | @Test 159 | public void getMetadataByServerUserIdCorrect() throws DAOException { 160 | 161 | /* 162 | * String query = "{ " + "'user': 'bb', " + "'type': 'get_metadata'," + 163 | * "'include_deleted': 'false' " + "}"; 164 | * 165 | * byte[] queryByte = query.getBytes(); 166 | * 167 | * GetMetadataMessage msg = (GetMetadataMessage) 168 | * reader.readMessage(queryByte); GetMetadataResponseMessage response = 169 | * handler.doGetMetadata(msg); 170 | * 171 | * assertTrue(response.getSucced()); 172 | * 173 | * printResponse(response); 174 | */ 175 | } 176 | 177 | private void printResponse(APIGetMetadata r) { 178 | String response = reader.createResponse(r); 179 | System.out.println(response); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/GetWorkspaceInfoTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.UUID; 7 | 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import com.stacksync.commons.models.ItemMetadata; 12 | import com.stacksync.commons.models.User; 13 | import com.stacksync.commons.models.Workspace; 14 | import com.stacksync.syncservice.db.ConnectionPool; 15 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 16 | import com.stacksync.syncservice.db.DAOFactory; 17 | import com.stacksync.syncservice.db.UserDAO; 18 | import com.stacksync.syncservice.db.WorkspaceDAO; 19 | import com.stacksync.syncservice.handler.APIHandler; 20 | import com.stacksync.syncservice.handler.SQLAPIHandler; 21 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 22 | import com.stacksync.syncservice.rpc.messages.APIGetWorkspaceInfoResponse; 23 | import com.stacksync.syncservice.util.Config; 24 | 25 | public class GetWorkspaceInfoTest { 26 | 27 | private static APIHandler handler; 28 | private static WorkspaceDAO workspaceDAO; 29 | private static UserDAO userDao; 30 | private static User user1; 31 | private static User user2; 32 | 33 | @BeforeClass 34 | public static void initializeData() throws Exception { 35 | 36 | Config.loadProperties(); 37 | 38 | String datasource = Config.getDatasource(); 39 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 40 | 41 | handler = new SQLAPIHandler(pool); 42 | DAOFactory factory = new DAOFactory(datasource); 43 | 44 | Connection connection = pool.getConnection(); 45 | 46 | 47 | workspaceDAO = factory.getWorkspaceDao(connection); 48 | userDao = factory.getUserDao(connection); 49 | 50 | user1 = new User(UUID.fromString("159a1286-33df-4453-bf80-cff4af0d97b0"), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L,0L, 0L); 51 | 52 | /* 53 | userDao.add(user1); 54 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 55 | workspaceDAO.add(workspace1); 56 | 57 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 58 | 59 | userDao.add(user2); 60 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 61 | workspaceDAO.add(workspace2); 62 | */ 63 | } 64 | 65 | @Test 66 | public void registerNewDevice() throws Exception { 67 | 68 | ItemMetadata file = new ItemMetadata(); 69 | file.setId(null); 70 | 71 | APIGetWorkspaceInfoResponse response = handler.getWorkspaceInfo(user1, file); 72 | System.out.println(response.toString()); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/SendShareNotificationTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.util.UUID; 4 | 5 | import omq.common.broker.Broker; 6 | 7 | import com.stacksync.commons.notifications.ShareProposalNotification; 8 | import com.stacksync.commons.omq.RemoteClient; 9 | import com.stacksync.syncservice.util.Config; 10 | 11 | public class SendShareNotificationTest { 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | Config.loadProperties(); 16 | Broker broker = new Broker(Config.getProperties()); 17 | 18 | ShareProposalNotification notification = new ShareProposalNotification(UUID.randomUUID(), "folder name", null, 19 | UUID.randomUUID(), "Owner name", "container999", "http://asdasddsa", false); 20 | 21 | RemoteClient client = broker.lookupMulti("AUTH_b9d5665bc46145b7985c2e0c37f817d1", RemoteClient.class); 22 | client.notifyShareProposal(notification); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/ShareFolderTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.Date; 7 | import java.util.List; 8 | import java.util.Random; 9 | import java.util.UUID; 10 | 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | 14 | import com.stacksync.commons.models.Item; 15 | import com.stacksync.commons.models.ItemMetadata; 16 | import com.stacksync.commons.models.User; 17 | import com.stacksync.commons.models.Workspace; 18 | import com.stacksync.syncservice.db.ConnectionPool; 19 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 20 | import com.stacksync.syncservice.db.DAOFactory; 21 | import com.stacksync.syncservice.db.UserDAO; 22 | import com.stacksync.syncservice.db.WorkspaceDAO; 23 | import com.stacksync.syncservice.handler.APIHandler; 24 | import com.stacksync.syncservice.handler.SQLAPIHandler; 25 | import com.stacksync.syncservice.handler.Handler.Status; 26 | import com.stacksync.syncservice.handler.SQLSyncHandler; 27 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 28 | import com.stacksync.syncservice.util.Config; 29 | import com.stacksync.syncservice.util.Constants; 30 | 31 | public class ShareFolderTest { 32 | 33 | private static SQLSyncHandler handler; 34 | private static WorkspaceDAO workspaceDAO; 35 | private static UserDAO userDao; 36 | private static User user1; 37 | private static User user2; 38 | 39 | @BeforeClass 40 | public static void initializeData() throws Exception { 41 | 42 | Config.loadProperties(); 43 | 44 | String datasource = Config.getDatasource(); 45 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 46 | 47 | handler = new SQLSyncHandler(pool); 48 | DAOFactory factory = new DAOFactory(datasource); 49 | 50 | Connection connection = pool.getConnection(); 51 | 52 | 53 | workspaceDAO = factory.getWorkspaceDao(connection); 54 | userDao = factory.getUserDao(connection); 55 | 56 | user1 = new User(UUID.fromString("159a1286-33df-4453-bf80-cff4af0d97b0"), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L,0L, 0L); 57 | 58 | /* 59 | userDao.add(user1); 60 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 61 | workspaceDAO.add(workspace1); 62 | 63 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 64 | 65 | userDao.add(user2); 66 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 67 | workspaceDAO.add(workspace2); 68 | */ 69 | } 70 | 71 | @Test 72 | public void shareFolder() throws Exception { 73 | 74 | List emails = new ArrayList(); 75 | emails.add("c@c.c"); 76 | Item item = new Item(125L); 77 | 78 | handler.doShareFolder(user1, emails, item, false); 79 | 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/SharingTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.UUID; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | import org.junit.AfterClass; 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | 14 | import com.stacksync.commons.exceptions.ShareProposalNotCreatedException; 15 | import com.stacksync.commons.exceptions.UserNotFoundException; 16 | import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException; 17 | import com.stacksync.commons.models.User; 18 | import com.stacksync.commons.models.Workspace; 19 | import com.stacksync.syncservice.db.ConnectionPool; 20 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 21 | import com.stacksync.syncservice.db.DAOFactory; 22 | import com.stacksync.syncservice.db.UserDAO; 23 | import com.stacksync.syncservice.db.WorkspaceDAO; 24 | import com.stacksync.syncservice.exceptions.dao.DAOException; 25 | import com.stacksync.syncservice.handler.Handler; 26 | import com.stacksync.syncservice.handler.SQLSyncHandler; 27 | import com.stacksync.syncservice.util.Config; 28 | 29 | public class SharingTest { 30 | 31 | private static Handler handler; 32 | private static WorkspaceDAO workspaceDAO; 33 | private static UserDAO userDao; 34 | private static User user1; 35 | private static User user2; 36 | private static Workspace workspace1; 37 | 38 | @BeforeClass 39 | public static void initializeData() throws Exception { 40 | 41 | Config.loadProperties(); 42 | 43 | String datasource = Config.getDatasource(); 44 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 45 | 46 | handler = new SQLSyncHandler(pool); 47 | DAOFactory factory = new DAOFactory(datasource); 48 | 49 | Connection connection = pool.getConnection(); 50 | 51 | workspaceDAO = factory.getWorkspaceDao(connection); 52 | userDao = factory.getUserDao(connection); 53 | 54 | user1 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L,0L, 0L); 55 | 56 | userDao.add(user1); 57 | workspace1 = new Workspace(null, 1, user1, false, false); 58 | workspaceDAO.add(workspace1); 59 | 60 | } 61 | 62 | @AfterClass 63 | public static void cleanData() throws DAOException { 64 | // userDao.delete("aa"); 65 | } 66 | 67 | /*@Test 68 | public void createShareProposal() throws DAOException, ShareProposalNotCreatedException, UserNotFoundException { 69 | 70 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 71 | 72 | userDao.add(user2); 73 | 74 | List emails = new ArrayList(); 75 | emails.add(user2.getEmail()); 76 | emails.add("fakemail@fake.com"); 77 | 78 | Workspace result = handler.doCreateShareProposal (user1, emails, "shared_folder", false); 79 | 80 | System.out.println("Result: " + result.getId()); 81 | 82 | assertNotEquals("-1", result.getId()); 83 | } 84 | 85 | @Test(expected = ShareProposalNotCreatedException.class) 86 | public void createShareProposalFakeMail() throws DAOException, ShareProposalNotCreatedException, 87 | UserNotFoundException { 88 | 89 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 90 | userDao.add(user2); 91 | 92 | 93 | List emails = new ArrayList(); 94 | emails.add("fakemail@fake.com"); 95 | 96 | Workspace result = handler.doCreateShareProposal(user1, emails, "shared_folder", false); 97 | 98 | System.out.println("Result: " + result.getId()); 99 | } 100 | 101 | @Test 102 | public void updateWorkspace() throws UserNotFoundException, WorkspaceNotUpdatedException { 103 | 104 | workspace1.setName("workspace_folder"); 105 | workspace1.setParentItem(null); 106 | 107 | handler.doUpdateWorkspace(user1, workspace1); 108 | }*/ 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/UpdateDataTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.UUID; 7 | 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import com.stacksync.commons.models.ItemMetadata; 12 | import com.stacksync.commons.models.User; 13 | import com.stacksync.commons.models.Workspace; 14 | import com.stacksync.syncservice.db.ConnectionPool; 15 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 16 | import com.stacksync.syncservice.db.DAOFactory; 17 | import com.stacksync.syncservice.db.UserDAO; 18 | import com.stacksync.syncservice.db.WorkspaceDAO; 19 | import com.stacksync.syncservice.handler.APIHandler; 20 | import com.stacksync.syncservice.handler.SQLAPIHandler; 21 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 22 | import com.stacksync.syncservice.util.Config; 23 | 24 | public class UpdateDataTest { 25 | 26 | private static APIHandler handler; 27 | private static WorkspaceDAO workspaceDAO; 28 | private static UserDAO userDao; 29 | private static User user1; 30 | private static User user2; 31 | 32 | @BeforeClass 33 | public static void initializeData() throws Exception { 34 | 35 | Config.loadProperties(); 36 | 37 | String datasource = Config.getDatasource(); 38 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 39 | 40 | handler = new SQLAPIHandler(pool); 41 | DAOFactory factory = new DAOFactory(datasource); 42 | 43 | Connection connection = pool.getConnection(); 44 | 45 | 46 | workspaceDAO = factory.getWorkspaceDao(connection); 47 | userDao = factory.getUserDao(connection); 48 | 49 | user1 = new User(UUID.fromString("225130d4-c817-4df0-b4e2-13271b494ae5"), "tester_2", "tester_2", "AUTH_5e446d39e4294b57831da7ce3dd0d2c2", "test@stacksync.org", 100000L,0L, 0L); 50 | 51 | /* 52 | userDao.add(user1); 53 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 54 | workspaceDAO.add(workspace1); 55 | 56 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 57 | 58 | userDao.add(user2); 59 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 60 | workspaceDAO.add(workspace2); 61 | */ 62 | } 63 | 64 | @Test 65 | public void registerNewDevice() throws Exception { 66 | 67 | ItemMetadata file = new ItemMetadata(); 68 | file.setId(509L); 69 | file.setMimetype("image/jpeg"); 70 | file.setChecksum(0000000000L); 71 | file.setSize(900L); 72 | file.setChunks(Arrays.asList("11111", "22222", "333333")); 73 | 74 | APICommitResponse response = handler.updateData(user1, file); 75 | System.out.println(response.toString()); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/UpdateDeviceTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.UUID; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | import org.junit.AfterClass; 9 | import org.junit.BeforeClass; 10 | import org.junit.Test; 11 | 12 | import com.stacksync.commons.models.Device; 13 | import com.stacksync.commons.models.User; 14 | import com.stacksync.commons.models.Workspace; 15 | import com.stacksync.syncservice.db.ConnectionPool; 16 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 17 | import com.stacksync.syncservice.db.DAOFactory; 18 | import com.stacksync.syncservice.db.UserDAO; 19 | import com.stacksync.syncservice.db.WorkspaceDAO; 20 | import com.stacksync.syncservice.exceptions.dao.DAOException; 21 | import com.stacksync.syncservice.handler.Handler; 22 | import com.stacksync.syncservice.handler.SQLSyncHandler; 23 | import com.stacksync.syncservice.util.Config; 24 | 25 | public class UpdateDeviceTest { 26 | 27 | private static Handler handler; 28 | private static WorkspaceDAO workspaceDAO; 29 | private static UserDAO userDao; 30 | private static User user1; 31 | private static User user2; 32 | 33 | @BeforeClass 34 | public static void initializeData() throws Exception { 35 | 36 | 37 | Config.loadProperties(); 38 | 39 | String datasource = Config.getDatasource(); 40 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 41 | 42 | handler = new SQLSyncHandler(pool); 43 | DAOFactory factory = new DAOFactory(datasource); 44 | 45 | Connection connection = pool.getConnection(); 46 | 47 | workspaceDAO = factory.getWorkspaceDao(connection); 48 | userDao = factory.getUserDao(connection); 49 | 50 | user1 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L, 0L, 0L); 51 | 52 | userDao.add(user1); 53 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 54 | workspaceDAO.add(workspace1); 55 | 56 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L, 0L, 0L); 57 | 58 | userDao.add(user2); 59 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 60 | workspaceDAO.add(workspace2); 61 | 62 | 63 | } 64 | 65 | @AfterClass 66 | public static void cleanData() throws DAOException { 67 | // userDao.delete("aa"); 68 | } 69 | 70 | /*@Test 71 | public void registerNewDevice() throws Exception { 72 | 73 | Device device = new Device(); 74 | device.setUser(user1); 75 | device.setName("john's computer"); 76 | device.setOs("Linux"); 77 | device.setLastIp("15.26.156.98"); 78 | device.setAppVersion("1.2.3"); 79 | 80 | UUID result = handler.doUpdateDevice(device); 81 | 82 | System.out.println("Result: " + result + " | Device: " + device); 83 | 84 | assertNotEquals("-1", result); 85 | } 86 | 87 | @Test 88 | public void updateExistingDevice() throws Exception { 89 | 90 | Device device = new Device(); 91 | device.setUser(user1); 92 | device.setName("john's computer"); 93 | device.setOs("Linux"); 94 | device.setLastIp("15.26.156.98"); 95 | device.setAppVersion("1.2.3"); 96 | 97 | UUID result1 = handler.doUpdateDevice(device); 98 | 99 | System.out.println("Result: " + result1 + " | Device: " + device); 100 | 101 | assertNotEquals("-1", result1); 102 | 103 | device.setLastIp("1.1.1.1"); 104 | device.setAppVersion("3.3.3"); 105 | 106 | UUID result2 = handler.doUpdateDevice(device); 107 | System.out.println("Result: " + result2 + " | Device: " + device); 108 | 109 | assertEquals(result1, result2); 110 | } 111 | 112 | @Test 113 | public void updateAlienDevice() throws Exception { 114 | 115 | Device device = new Device(); 116 | device.setUser(user1); 117 | device.setName("john's computer"); 118 | device.setOs("Linux"); 119 | device.setLastIp("15.26.156.98"); 120 | device.setAppVersion("1.2.3"); 121 | 122 | UUID result = handler.doUpdateDevice(device); 123 | 124 | System.out.println("Result: " + result + " | Device: " + device); 125 | 126 | device.setUser(user2); 127 | device.setLastIp("1.1.1.1"); 128 | device.setAppVersion("3.3.3"); 129 | 130 | result = handler.doUpdateDevice(device); 131 | 132 | System.out.println("Result: " + result + " | Device: " + device); 133 | 134 | assertEquals("-1", result); 135 | }*/ 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/handler/UpdateMetadataTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.handler; 2 | 3 | import java.sql.Connection; 4 | import java.util.UUID; 5 | 6 | import org.junit.BeforeClass; 7 | import org.junit.Test; 8 | 9 | import com.stacksync.commons.models.ItemMetadata; 10 | import com.stacksync.commons.models.User; 11 | import com.stacksync.commons.models.Workspace; 12 | import com.stacksync.syncservice.db.ConnectionPool; 13 | import com.stacksync.syncservice.db.ConnectionPoolFactory; 14 | import com.stacksync.syncservice.db.DAOFactory; 15 | import com.stacksync.syncservice.db.UserDAO; 16 | import com.stacksync.syncservice.db.WorkspaceDAO; 17 | import com.stacksync.syncservice.handler.APIHandler; 18 | import com.stacksync.syncservice.handler.SQLAPIHandler; 19 | import com.stacksync.syncservice.rpc.messages.APICommitResponse; 20 | import com.stacksync.syncservice.util.Config; 21 | 22 | public class UpdateMetadataTest { 23 | 24 | private static APIHandler handler; 25 | private static WorkspaceDAO workspaceDAO; 26 | private static UserDAO userDao; 27 | private static User user1; 28 | private static User user2; 29 | 30 | @BeforeClass 31 | public static void initializeData() throws Exception { 32 | 33 | Config.loadProperties(); 34 | 35 | String datasource = Config.getDatasource(); 36 | ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); 37 | 38 | handler = new SQLAPIHandler(pool); 39 | DAOFactory factory = new DAOFactory(datasource); 40 | 41 | Connection connection = pool.getConnection(); 42 | 43 | 44 | workspaceDAO = factory.getWorkspaceDao(connection); 45 | userDao = factory.getUserDao(connection); 46 | 47 | user1 = new User(UUID.fromString("159a1286-33df-4453-bf80-cff4af0d97b0"), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100L, 0L, 0L); 48 | 49 | /* 50 | userDao.add(user1); 51 | Workspace workspace1 = new Workspace(null, 1, user1, false, false); 52 | workspaceDAO.add(workspace1); 53 | 54 | user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "a@a.a", 100, 0); 55 | 56 | userDao.add(user2); 57 | Workspace workspace2 = new Workspace(null, 1, user2, false, false); 58 | workspaceDAO.add(workspace2); 59 | */ 60 | } 61 | 62 | @Test 63 | public void registerNewDevice() throws Exception { 64 | 65 | ItemMetadata file = new ItemMetadata(); 66 | file.setId(118L); 67 | file.setFilename("chunks-2.png"); 68 | file.setParentId(null); 69 | 70 | APICommitResponse response = handler.updateMetadata(user1, file, false); 71 | System.out.println(response.toString()); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/main/ServerTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.main; 2 | 3 | 4 | import org.apache.commons.daemon.DaemonContext; 5 | import org.apache.commons.daemon.DaemonController; 6 | 7 | import com.stacksync.syncservice.SyncServiceDaemon; 8 | 9 | public class ServerTest { 10 | 11 | public static void main(String[] args) throws Exception { 12 | 13 | SyncServiceDaemon daemon = new SyncServiceDaemon(); 14 | try { 15 | DaemonContext dc = new DaemonContext() { 16 | 17 | @Override 18 | public DaemonController getController() { 19 | return null; 20 | } 21 | 22 | @Override 23 | public String[] getArguments() { 24 | return new String[]{"/home/edgar/Documents/stackSync/sync-service/config.properties"}; 25 | } 26 | }; 27 | 28 | daemon.init(dc); 29 | daemon.start(); 30 | } catch (Exception e) { 31 | throw e; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/reader/JSONParserTest.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.reader; 2 | 3 | import org.junit.BeforeClass; 4 | import org.junit.Test; 5 | 6 | import com.stacksync.syncservice.rpc.parser.JSONParser; 7 | 8 | public class JSONParserTest { 9 | 10 | private static JSONParser reader; 11 | private static String commitMsgSimple; 12 | private static byte[] commitMsgByteSimple; 13 | private static String commitMsgMulti; 14 | private static byte[] commitMsgByteMulti; 15 | 16 | 17 | @BeforeClass 18 | public static void initializeData() { 19 | 20 | reader = new JSONParser(); 21 | 22 | commitMsgSimple = "{" + 23 | "'user':'user1'," + 24 | "'type':'commit'," + 25 | "'workspace':'user1/'," + 26 | "'requestId':'cotes_lab-1361792472697'," + 27 | "'device':'cotes_lab'," + 28 | "'metadata':[{" + 29 | "'rootId':'stacksync'," + 30 | "'fileId':6191744574108779128," + 31 | "'version':1," + 32 | "'parentRootId':''," + 33 | "'parentFileId':''," + 34 | "'parentFileVersion':''," + 35 | "'updated':1361792469869," + 36 | "'status':'NEW'," + 37 | "'lastModified':1360830516000," + 38 | "'checksum':3499525671," + 39 | "'clientName':'cotes_lab'," + 40 | "'fileSize':1968," + 41 | "'folder':'0'," + 42 | "'name':'pgadmin.log'," + 43 | "'path':'/'," + 44 | "'mimetype':'text/plain'," + 45 | "'chunks':['29ECAA1D936E746D032C1A264A619746C3B5A7E4']}]}"; 46 | 47 | commitMsgByteSimple = commitMsgSimple.getBytes(); 48 | 49 | commitMsgMulti = "{" + 50 | "'user':'user1'," + 51 | "'type':'commit'," + 52 | "'workspace':'user1/'," + 53 | "'requestId':'cotes_lab-1361792472697'," + 54 | "'device':'cotes_lab'," + 55 | "'metadata':[{" + 56 | "'rootId':'stacksync'," + 57 | "'fileId':6191744574108779128," + 58 | "'version':1," + 59 | "'parentRootId':''," + 60 | "'parentFileId':''," + 61 | "'parentFileVersion':''," + 62 | "'updated':1361792469869," + 63 | "'status':'NEW'," + 64 | "'lastModified':1360830516000," + 65 | "'checksum':3499525671," + 66 | "'clientName':'cotes_lab'," + 67 | "'fileSize':1968," + 68 | "'folder':'0'," + 69 | "'name':'pgadmin.log'," + 70 | "'path':'/'," + 71 | "'mimetype':'text/plain'," + 72 | "'chunks':['29ECAA1D936E746D032C1A264A619746C3B5A7E4']}," + 73 | "{"+ 74 | "'rootId':'stacksync'," + 75 | "'fileId':6191744574108779128," + 76 | "'version':2," + 77 | "'parentRootId':''," + 78 | "'parentFileId':''," + 79 | "'parentFileVersion':''," + 80 | "'updated':1361792469000," + 81 | "'status':'CHANGED'," + 82 | "'lastModified':1360830517000," + 83 | "'checksum':3499525600," + 84 | "'clientName':'cotes_lab'," + 85 | "'fileSize':1900," + 86 | "'folder':'0'," + 87 | "'name':'pgadmin.log'," + 88 | "'path':'/'," + 89 | "'mimetype':'text/plain'," + 90 | "'chunks':['29ECAA1D936E746D032C1A264A619746C3B5A000','111CAA1D936E746D032C1A264A619746C3B5A000']}]}"; 91 | 92 | commitMsgByteMulti = commitMsgMulti.getBytes(); 93 | } 94 | 95 | @Test 96 | public void testCreateResponse() { 97 | 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiCreateFolder.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiCreateFolder { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 13 | config.setEnabledForExtensions(true); 14 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 15 | XmlRpcClient client = new XmlRpcClient(); 16 | client.setConfig(config); 17 | 18 | String strUserId = "159a1286-33df-4453-bf80-cff4af0d97b0"; 19 | String strFolderName = "folder1"; 20 | String strParentId = "null"; 21 | 22 | Object[] params = new Object[] { strUserId, strFolderName, strParentId}; 23 | 24 | long startTotal = System.currentTimeMillis(); 25 | String strResponse = (String) client.execute("XmlRpcSyncHandler.createFolder", params); 26 | 27 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 28 | 29 | long totalTime = System.currentTimeMillis() - startTotal; 30 | System.out.println("Total level time --> " + totalTime + " ms"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiDeleteMetadataFile.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiDeleteMetadataFile { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 13 | config.setEnabledForExtensions(true); 14 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 15 | XmlRpcClient client = new XmlRpcClient(); 16 | client.setConfig(config); 17 | 18 | Object[] params = new Object[] { Constants.USER, Constants.REQUESTID, "-4573748213815439639"}; 19 | // strFileId 20 | 21 | long startTotal = System.currentTimeMillis(); 22 | String strResponse = (String) client.execute("XmlRpcSyncHandler.deleteMetadataFile", params); 23 | 24 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 25 | 26 | long totalTime = System.currentTimeMillis() - startTotal; 27 | System.out.println("Total level time --> " + totalTime + " ms"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiGetMetadata.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiGetMetadata { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 13 | config.setEnabledForExtensions(true); 14 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 15 | XmlRpcClient client = new XmlRpcClient(); 16 | client.setConfig(config); 17 | 18 | String strUserId = "159a1286-33df-4453-bf80-cff4af0d97b0"; 19 | String strItemId = "100"; 20 | String strIncludeList = "true"; 21 | String strIncludeDeleted = "true"; 22 | String strIncludeChunks = "true"; 23 | String strVersion = "null"; 24 | 25 | Object[] params = new Object[] { strUserId, strItemId, strIncludeList, strIncludeDeleted, strIncludeChunks, strVersion}; 26 | 27 | long startTotal = System.currentTimeMillis(); 28 | String strResponse = (String) client.execute("XmlRpcSyncHandler.getMetadata", params); 29 | 30 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 31 | 32 | long totalTime = System.currentTimeMillis() - startTotal; 33 | System.out.println("Total level time --> " + totalTime + " ms"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiGetVersions.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiGetVersions { 9 | 10 | public static void main(String[] args) throws Exception { 11 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 12 | config.setEnabledForExtensions(true); 13 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 14 | XmlRpcClient client = new XmlRpcClient(); 15 | client.setConfig(config); 16 | 17 | Object[] params = new Object[] { Constants.USER, Constants.REQUESTID, "887611628764801051" }; 18 | // strFileId 19 | 20 | long startTotal = System.currentTimeMillis(); 21 | String strResponse = (String) client.execute("XmlRpcSyncHandler.getVersions", params); 22 | 23 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 24 | 25 | long totalTime = System.currentTimeMillis() - startTotal; 26 | System.out.println("Total level time --> " + totalTime + " ms"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiPutMetadataFile.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiPutMetadataFile { 9 | 10 | 11 | //TODO: sube de version siempre aunque sea igual 12 | //TODO: overwrite 13 | public static void main(String[] args) throws Exception { 14 | 15 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 16 | config.setEnabledForExtensions(true); 17 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 18 | XmlRpcClient client = new XmlRpcClient(); 19 | client.setConfig(config); 20 | 21 | String[] chunks = new String[] {"1111", "2222", "3333"}; 22 | Object[] params = new Object[] { Constants.USER, Constants.REQUESTID, "test.txt", "", "", "111111", "10", "Text", chunks}; 23 | // strFileName, strParentId, strOverwrite, strChecksum, strFileSize, 24 | // strMimetype, strChunks 25 | 26 | long startTotal = System.currentTimeMillis(); 27 | String strResponse = (String) client.execute("XmlRpcSyncHandler.putMetadataFile", params); 28 | 29 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 30 | 31 | long totalTime = System.currentTimeMillis() - startTotal; 32 | System.out.println("Total level time --> " + totalTime + " ms"); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiPutMetadataFolder.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiPutMetadataFolder { 9 | 10 | //TODO: probar con el mismo nombre de un archivo 11 | //TODO: corregir path cuando la carpeta esta dentro de otra. 12 | public static void main(String[] args) throws Exception { 13 | 14 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 15 | config.setEnabledForExtensions(true); 16 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 17 | XmlRpcClient client = new XmlRpcClient(); 18 | client.setConfig(config); 19 | 20 | Object[] params = new Object[] { Constants.USER, Constants.REQUESTID, "hola5", null}; 21 | // strFolderName, strParentId 22 | 23 | long startTotal = System.currentTimeMillis(); 24 | String strResponse = (String) client.execute("XmlRpcSyncHandler.putMetadataFolder", params); 25 | 26 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 27 | 28 | long totalTime = System.currentTimeMillis() - startTotal; 29 | System.out.println("Total level time --> " + totalTime + " ms"); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiRestoreMetadata.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import java.net.URL; 4 | 5 | import org.apache.xmlrpc.client.XmlRpcClient; 6 | import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; 7 | 8 | public class ApiRestoreMetadata { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 13 | config.setEnabledForExtensions(true); 14 | config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT)); 15 | XmlRpcClient client = new XmlRpcClient(); 16 | client.setConfig(config); 17 | 18 | Object[] params = new Object[] { Constants.USER, Constants.REQUESTID, "887611628764801051", "2"}; 19 | // strFileId, strVersion 20 | 21 | long startTotal = System.currentTimeMillis(); 22 | String strResponse = (String) client.execute("XmlRpcSyncHandler.restoreMetadata", params); 23 | 24 | System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse)); 25 | 26 | long totalTime = System.currentTimeMillis() - startTotal; 27 | System.out.println("Total level time --> " + totalTime + " ms"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/stacksync/syncservice/test/xmlrpc/Constants.java: -------------------------------------------------------------------------------- 1 | package com.stacksync.syncservice.test.xmlrpc; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import com.google.gson.JsonElement; 6 | import com.google.gson.JsonParser; 7 | 8 | public class Constants { 9 | public static String USER = "AUTH_6d3b65697d5c48d5aaffbb430c9dbe6a"; 10 | public static String WORKSPACEID = "AUTH_6d3b65697d5c48d5aaffbb430c9dbe6a/"; 11 | public static String REQUESTID = "TestXmlRpc"; 12 | public static String DEVICENAME = "Test-Device"; 13 | public static Integer XMLRPC_PORT = com.stacksync.syncservice.util.Constants.XMLRPC_PORT; 14 | 15 | public static String PrettyPrintJson(String uglyJSONString){ 16 | Gson gson = new GsonBuilder().setPrettyPrinting().create(); 17 | JsonParser jp = new JsonParser(); 18 | JsonElement je = jp.parse(uglyJSONString); 19 | String prettyJsonString = gson.toJson(je); 20 | 21 | return prettyJsonString; 22 | } 23 | } 24 | --------------------------------------------------------------------------------