├── inst ├── resources │ └── test │ │ ├── withHeaders.csv │ │ ├── test.csv │ │ ├── testFunction2.R │ │ ├── testFunction.R │ │ ├── org │ │ └── sagebionetworks │ │ │ └── test │ │ │ └── Test.json │ │ └── Test.json ├── images │ └── synapse_banner.gif ├── certificateBundle │ └── .svn │ │ └── all-wcprops ├── unitTests │ ├── test_SimplePropertyOwner.R │ ├── test_QueryResult.R │ ├── test_synToJson.R │ ├── test_checkLatestVersion.R │ ├── test_usedListEntry.R │ ├── test_mergeColumns.R │ ├── test_AAAShared.R │ ├── test_tableSchema.R │ ├── test_queryLimitAndOffset.R │ ├── test_FileNameFromHeaders.R │ ├── test_memoryCache.R │ ├── test_downloadFromServiceWithCaching.R │ ├── test_getEntityInstance.R │ ├── test_submit.R │ ├── test_getCachedInLocation.R │ ├── test_table.R │ ├── test_synPropAndAnnot.R │ ├── test_uploadFile.R │ ├── test_URL.R │ └── test_typedList.R └── integrationTests │ ├── test_getMimeTypeForFile.R │ ├── test_createEntity.R │ ├── test_tableColumn.R │ ├── test_userProfile.R │ ├── test_versions.R │ ├── test_fileHandleService.R │ ├── test_entityFileAccess.R │ ├── test_externalFileHandle.R │ ├── test_asTableColumns.R │ └── test_exclusiveFileAccess.R ├── R ├── generateAnnotationsUri.R ├── isScalar.R ├── generateActivityUri.R ├── touOnWeb.R ├── generateEntityUri.R ├── getAnnotations.R ├── available.versions.R ├── listToString.R ├── sendMessage.R ├── buildSynapseUrl.R ├── isSynapseId.R ├── rowMerge.R ├── updateS4Object.R ├── createS4Object.R ├── synapseVersionsServiceEndpoint.R ├── jsonListToDataFrame.R ├── logErrorToSynapse.R ├── parseJSONRecords.R ├── now.R ├── getParentEntity.R ├── synFromJson.R ├── parseSingleRow.R ├── refreshSessionToken.R ├── synapseResetEndpoints.R ├── TableColumn.R ├── defineS4MethodsForAutogenClasses.R ├── deleteEntity.R ├── getServerVersion.R ├── AAAGlobalCache.R ├── getReference.R ├── synapseLinkExternalFile.R ├── synapseDelete.R ├── getVersionInfo.R ├── synapseGet.R ├── synapsePost.R ├── synapsePut.R ├── synapseEndpoints.R ├── onWeb.R ├── userProfile.R ├── synapseRequest.R ├── synapseCacheDir.R ├── checkInteger.R ├── getEntityInstance.R ├── synapseQuery.R ├── loadEntity.R ├── SynRest.R ├── checkCurlResponse.R ├── queryLimitAndOffset.R ├── xxxAccessControlList.R ├── Config.R ├── resolvePermanentRedirect.R ├── asTableColumns.R ├── synapseServiceEndpoint.R ├── uploadStringToFile.R ├── downloadEntity.R ├── checkLatestVersion.R ├── withRetries.R ├── curlWriter.R ├── mergeColumns.R ├── SynPropertiesAndAnnotations.R ├── getMimeTypeForFile.R ├── webRequestWithRetries.R └── createListFromS4Object.R ├── src ├── synapse_curl.h ├── R_init_Synapse.c └── synapse_curl.c ├── man ├── synGetEndpoints.Rd ├── onWeb.Rd ├── length.Rd ├── names.Rd ├── hmacSecretKey.Rd ├── setPackageName.Rd ├── touOnWeb.Rd ├── WikiHeader.Rd ├── as.list.Rd ├── annotations-methods.Rd ├── onWeb-methods.Rd ├── getParentEntity-methods.Rd ├── annotationNames.Rd ├── getActivity-methods.Rd ├── properties.Rd ├── generatedBy.Rd ├── synapseCacheDir.Rd ├── synGetColumns.Rd ├── properties-methods.Rd ├── synGetActivity.Rd ├── synDelete.Rd ├── UserProfile.Rd ├── propertyNames.Rd ├── propertyValues-methods.Rd ├── generatedBy_--methods.Rd ├── TableSchema.Rd ├── getFileLocation.Rd ├── propertyValue-methods.Rd ├── annotationValues-methods.Rd ├── propertyValues_--methods.Rd ├── synAddColumn.Rd ├── synGetWiki.Rd ├── used.Rd ├── annotValue-methods.Rd ├── synapseClient-package.Rd ├── synDeleteEntityACL.Rd ├── synRemoveColumn.Rd ├── executed.Rd ├── deleteProperty-methods.Rd ├── SubmissionStatus.Rd ├── deleteAnnotation-methods.Rd ├── synAnnot.Rd ├── synGetProperty.Rd ├── synSetProperty.Rd ├── synGetProperties.Rd ├── synSetProperties.Rd ├── synGetAnnotations.Rd ├── synGetAnnotation.Rd ├── synGetWikiHeaders.Rd ├── synSetAnnotation.Rd ├── synSetEndpoints.Rd ├── synCreateEntityACL.Rd ├── annotationValues_--methods.Rd ├── synUpdateEntityACL.Rd ├── synGetEntityACL.Rd ├── sendMessage.Rd ├── used_--methods.Rd ├── executed_--methods.Rd ├── synDeleteRows.Rd ├── synSetAnnotations.Rd ├── synGetSubmissionStatus.Rd ├── SynapseEntity.Rd ├── synapseAuthServiceEndpoint.Rd ├── synGetUserProfile.Rd ├── synDownloadTableColumns.Rd ├── synTableQuery.Rd ├── propertyValue_--methods.Rd ├── synGetOwnSubmissions.Rd ├── Activity.Rd ├── synGetEvaluation.Rd ├── setApiCredentials.Rd ├── annotations.Rd ├── synGetSubmissions.Rd ├── submit.Rd ├── WikiPage.Rd ├── Project.Rd ├── sessionToken.Rd ├── synGetSubmission.Rd ├── synapseREST.Rd ├── synRest.Rd ├── synGet.Rd ├── Folder.Rd ├── synapseLogin.Rd ├── annotValue_--methods.Rd ├── asTableColumns.Rd ├── Table.Rd ├── QueryResult.Rd └── synapseQuery.Rd ├── tools └── docGen │ ├── asTypedListTemplate.Rd │ └── typedListTemplate.Rd ├── .gitignore ├── configure ├── synapseRClient-assembly.xml ├── DESCRIPTION ├── README.markdown └── pom.xml /inst/resources/test/withHeaders.csv: -------------------------------------------------------------------------------- 1 | "string","numeric","integer","logical" "a1","1.234","0","TRUE" "a2","5.678","1","FALSE" -------------------------------------------------------------------------------- /R/generateAnnotationsUri.R: -------------------------------------------------------------------------------- 1 | .generateAnnotationsUri <- 2 | function(id) 3 | { 4 | sprintf("/entity/%s/annotations", id) 5 | } -------------------------------------------------------------------------------- /inst/images/synapse_banner.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sage-Bionetworks/rSynapseClient/HEAD/inst/images/synapse_banner.gif -------------------------------------------------------------------------------- /inst/resources/test/test.csv: -------------------------------------------------------------------------------- 1 | "R_Integration_Test_Column_1","R_Integration_Test_Column_2","R_Integration_Test_Column_3" "a1","b1","c1" "a2","b2","c2" -------------------------------------------------------------------------------- /R/isScalar.R: -------------------------------------------------------------------------------- 1 | # 2 | # check whether a variable is a scalar 3 | # 4 | 5 | is.scalar<-function(x) {!is.list(x) && (!is.vector(x) || length(x)<2)} 6 | 7 | -------------------------------------------------------------------------------- /R/generateActivityUri.R: -------------------------------------------------------------------------------- 1 | # 2 | # A method to generate the URI for doing Activity CRUD 3 | # 4 | .generateActivityUri<-function(id) { 5 | paste("/activity", id, sep="/") 6 | } -------------------------------------------------------------------------------- /R/touOnWeb.R: -------------------------------------------------------------------------------- 1 | # 2 | # Show Synapse Terms of Use in web browser 3 | # 4 | touOnWeb<-function() { 5 | utils::browseURL(sprintf("%s/termsOfUse.html", synapseAuthServiceEndpoint()$endpoint)) 6 | } -------------------------------------------------------------------------------- /R/generateEntityUri.R: -------------------------------------------------------------------------------- 1 | .generateEntityUri <- 2 | function(id, version=NULL) 3 | { 4 | uri <- paste("/entity/", id, sep="") 5 | if (!is.null(version)) uri <- paste(uri, "/version/", version, sep="") 6 | uri 7 | } -------------------------------------------------------------------------------- /R/getAnnotations.R: -------------------------------------------------------------------------------- 1 | setMethod( 2 | f = "getAnnotations", 3 | signature = "character", 4 | definition = function(entity){ 5 | uri <- .generateAnnotationsUri(entity) 6 | SynapseAnnotations(synapseGet(uri)) 7 | } 8 | ) -------------------------------------------------------------------------------- /src/synapse_curl.h: -------------------------------------------------------------------------------- 1 | /* Initialize c functions for curl writer in R 2 | * 3 | * Author: Martin Morgan 4 | */ 5 | #ifndef WRITER_H 6 | #define WRITER_H 7 | 8 | SEXP writer_open(SEXP filename); 9 | SEXP writer_close(SEXP ext); 10 | #endif 11 | -------------------------------------------------------------------------------- /inst/resources/test/testFunction2.R: -------------------------------------------------------------------------------- 1 | # This is a modification of testFunction 2 | # It's used by copying to a file called testFunction.R in a temp dir 3 | 4 | testFunction<-function(x) { 5 | internalFunction(x) 6 | } 7 | 8 | internalFunction<-function(x) { 9 | x+2 10 | } -------------------------------------------------------------------------------- /R/available.versions.R: -------------------------------------------------------------------------------- 1 | setMethod( 2 | f = "available.versions", 3 | signature = "character", 4 | definition = function(object){ 5 | if(is.null(object) || object == "") 6 | return(NULL) 7 | .jsonListToDataFrame(synapseGet(sprintf("/entity/%s/version", object))$results) 8 | } 9 | ) 10 | -------------------------------------------------------------------------------- /man/synGetEndpoints.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetEndpoints} 2 | \alias{synGetEndpoints} 3 | \title{ 4 | synGetEndpoints 5 | } 6 | 7 | \usage{ 8 | synGetEndpoints() 9 | } 10 | \value{ 11 | The current settings for the repo, auth, file, and portal endpoints. 12 | } 13 | \seealso{ 14 | \code{\link{synSetEndpoints}} 15 | } 16 | -------------------------------------------------------------------------------- /inst/resources/test/testFunction.R: -------------------------------------------------------------------------------- 1 | # This is a test file used to exerciese synapseExecute 2 | # It feature a function named after the file (testFunction) 3 | # as well as a second function 4 | 5 | testFunction<-function(x) { 6 | internalFunction(x) 7 | } 8 | 9 | internalFunction<-function(x) { 10 | x+1 11 | } -------------------------------------------------------------------------------- /inst/certificateBundle/.svn/all-wcprops: -------------------------------------------------------------------------------- 1 | K 25 2 | svn:wc:ra_dav:version-url 3 | V 74 4 | /svn/!svn/ver/4310/PLFM/trunk/client/rSynapseClient/inst/certificateBundle 5 | END 6 | cacert.pem 7 | K 25 8 | svn:wc:ra_dav:version-url 9 | V 85 10 | /svn/!svn/ver/4310/PLFM/trunk/client/rSynapseClient/inst/certificateBundle/cacert.pem 11 | END 12 | -------------------------------------------------------------------------------- /man/onWeb.Rd: -------------------------------------------------------------------------------- 1 | \name{onWeb} 2 | \alias{onWeb} 3 | \title{ 4 | View an Entity's Synapse Web Page 5 | } 6 | \description{ 7 | Show an Entity on The Synapse Website 8 | } 9 | \usage{ 10 | onWeb(entity) 11 | } 12 | %- maybe also 'usage' for other objects documented here. 13 | \arguments{ 14 | \item{entity}{ 15 | %% ~~Describe \code{entity} here~~ 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /man/length.Rd: -------------------------------------------------------------------------------- 1 | \name{length} 2 | \alias{length} 3 | \docType{methods} 4 | \title{ 5 | length 6 | } 7 | \description{ 8 | variation of length() for certain S-4 objects in the synapseClient package 9 | } 10 | \usage{ 11 | length(EnhancedEnvironment) 12 | length(QueryResult) 13 | } 14 | \details{ 15 | This function is deprecated and will be removed. Do not use. 16 | } 17 | 18 | -------------------------------------------------------------------------------- /R/listToString.R: -------------------------------------------------------------------------------- 1 | # This utility converts 2 | # list(foo="a", bar="b") 3 | # to the string 4 | # "foo=a,bar=b" 5 | # 6 | # Author: brucehoff 7 | ############################################################################### 8 | 9 | 10 | listToString<-function(x) { 11 | paste(lapply(names(x), function(n,x){sprintf("%s=%s",n, x[[n]])}, x), collapse=",") 12 | } 13 | -------------------------------------------------------------------------------- /man/names.Rd: -------------------------------------------------------------------------------- 1 | \name{names} 2 | \alias{names} 3 | \docType{methods} 4 | \title{ 5 | names 6 | } 7 | \description{ 8 | variation of names() for certain S-4 objects in the synapseClient package 9 | } 10 | \usage{ 11 | names(Entity) 12 | names(QueryResult) 13 | names(SynapseProperties) 14 | } 15 | \details{ 16 | This function is deprecated and will be removed. Do not use. 17 | } 18 | 19 | -------------------------------------------------------------------------------- /man/hmacSecretKey.Rd: -------------------------------------------------------------------------------- 1 | \name{hmacSecretKey} 2 | \alias{hmacSecretKey} 3 | \title{ 4 | hmacSecretKey 5 | } 6 | \description{ 7 | Retrieves the user-specific API key used to sign authenticated requests. 8 | } 9 | \usage{ 10 | hmacSecretKey() 11 | } 12 | \value{ 13 | A character string. 14 | } 15 | \seealso{ 16 | \code{\link{synapseLogin}} 17 | \code{\link{setApiCredentials}} 18 | } 19 | 20 | -------------------------------------------------------------------------------- /man/setPackageName.Rd: -------------------------------------------------------------------------------- 1 | \name{setPackageName} 2 | \alias{setPackageName} 3 | \docType{methods} 4 | \title{ 5 | setPackageName 6 | } 7 | \description{ 8 | variation of setPackageName() for certain S-4 objects in the synapseClient package 9 | } 10 | \usage{ 11 | setPackageName(where, create=TRUE) 12 | } 13 | \details{ 14 | This function is deprecated and will be removed. Do not use. 15 | } 16 | 17 | -------------------------------------------------------------------------------- /R/sendMessage.R: -------------------------------------------------------------------------------- 1 | ## Send message to users 2 | ## 3 | ## Author: Bruce Hoff 4 | ############################################################################## 5 | sendMessage<-function(userIdList, subject, body) { 6 | fileHandle<-uploadStringToSynapseS3File(body) 7 | messageContent <- list(recipients=userIdList, fileHandleId=fileHandle$id, subject=subject) 8 | synRestPOST("/message", messageContent) 9 | } -------------------------------------------------------------------------------- /R/buildSynapseUrl.R: -------------------------------------------------------------------------------- 1 | ## build a synapse url. for use by onweb function to open the entity 2 | ## page on the synapse web client. 3 | ## 4 | ## Author: Matthew D. Furia 5 | ############################################################################### 6 | 7 | .buildSynapseUrl <- 8 | function(entity) 9 | { 10 | url <- sprintf("%s/#Synapse:%s", synapsePortalEndpoint()$endpoint, entity) 11 | } 12 | -------------------------------------------------------------------------------- /inst/unitTests/test_SimplePropertyOwner.R: -------------------------------------------------------------------------------- 1 | # TODO: test for SYNR-529 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | # tests that SYNR-529 is fixed 8 | unitTestDollarAssignment <-function() 9 | { 10 | e<-Evaluation() 11 | checkTrue(is(e, "Evaluation")) 12 | e$id<-"123" 13 | checkTrue(is(e, "Evaluation")) 14 | checkEquals("123", e$id) 15 | } 16 | -------------------------------------------------------------------------------- /R/isSynapseId.R: -------------------------------------------------------------------------------- 1 | # TODO: Add comment 2 | # 3 | # Author: bhoff 4 | ############################################################################### 5 | 6 | 7 | isSynapseId<-function(s) { 8 | if (!(class(s)=="character" && length(s)==1 && substr(s, 1, 3)=="syn" && nchar(s)>3)) { 9 | F 10 | } else { 11 | # now check whether the suffix is numeric 12 | any(grep("^[[:digit:]]*$", substr(s, 4, nchar(s)))) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /R/rowMerge.R: -------------------------------------------------------------------------------- 1 | ## Utility function for merging tables by row 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################## 5 | 6 | .rowMerge <- 7 | function(table1, newRow) 8 | { 9 | rowNumber <- nrow(table1) + 1 10 | for(colName in names(newRow)){ 11 | table1[rowNumber, colName] <- newRow[1,colName] 12 | } 13 | return(table1) 14 | } 15 | -------------------------------------------------------------------------------- /man/touOnWeb.Rd: -------------------------------------------------------------------------------- 1 | \name{touOnWeb} 2 | \alias{touOnWeb} 3 | \title{ 4 | View the Synapse Terms of Use as a Web Page 5 | } 6 | \description{ 7 | Show the Synapse Terms of Use as a Web Page 8 | } 9 | \usage{ 10 | touOnWeb() 11 | } 12 | \details{ 13 | Opens the default web browser to the Synapse Terms of Use web page. These are the same general Terms of Use you must agree to, before being allowed to log in to Synapse. 14 | } 15 | 16 | 17 | -------------------------------------------------------------------------------- /man/WikiHeader.Rd: -------------------------------------------------------------------------------- 1 | \name{WikiHeader} 2 | \alias{WikiHeader} 3 | \docType{methods} 4 | \title{ 5 | Constructor for WikiHeader 6 | } 7 | \description{ 8 | Constructor for WikiHeader 9 | } 10 | \usage{ 11 | WikiHeader(id, title, parentId) 12 | } 13 | \details{ 14 | This constructor is not used directly. Instances are returned by synGetWkiHeaders(). 15 | } 16 | \seealso{ 17 | \code{\link{synGetWikiHeaders}} 18 | \code{\link{synGetWiki}} 19 | } 20 | -------------------------------------------------------------------------------- /R/updateS4Object.R: -------------------------------------------------------------------------------- 1 | # update method for auto-generated S4 objects 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | updateS4Object<-function(object, updateUri) { 7 | objectAsList<-createListFromS4Object(object) 8 | listResult<-synRestPUT(updateUri, objectAsList) 9 | objectResult<-createS4ObjectFromList(listResult, class(object)) 10 | objectResult 11 | } 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /man/as.list.Rd: -------------------------------------------------------------------------------- 1 | \name{as.list} 2 | \alias{as.list} 3 | \docType{methods} 4 | \title{ 5 | as.list 6 | } 7 | \description{ 8 | variation of as.list() for certain S-4 objects in the synapseClient package 9 | } 10 | \usage{ 11 | as.list(SimplePropertyOwner) 12 | as.list(SynapseAnnotations) 13 | as.list(TypedPropertyStore) 14 | as.list(SynapseProperties) 15 | } 16 | \details{ 17 | This function is deprecated and will be removed. Do not use. 18 | } 19 | 20 | -------------------------------------------------------------------------------- /R/createS4Object.R: -------------------------------------------------------------------------------- 1 | # create method for auto-generated S4 objects 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | createS4Object<-function(object, createUri) { 7 | objectAsList<-createListFromS4Object(object) 8 | listResult<-synRestPOST(createUri, objectAsList) 9 | objectResult<-createS4ObjectFromList(listResult, class(object)) 10 | objectResult 11 | } 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /man/annotations-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{annotations-methods} 2 | \docType{methods} 3 | \alias{annotations-methods} 4 | \alias{annotations,SynapseEntity-method} 5 | \title{ Methods for Function \code{annotations} } 6 | \description{ 7 | Methods for function \code{annotations} 8 | } 9 | \section{Methods}{ 10 | \describe{ 11 | 12 | \item{\code{signature(object = "SynapseEntity")}}{ 13 | Set the annotations for a SynapseEntity 14 | } 15 | }} 16 | \keyword{methods} 17 | -------------------------------------------------------------------------------- /man/onWeb-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{onWeb-methods} 2 | \docType{methods} 3 | \alias{onWeb-methods} 4 | \alias{onWeb,SynapseEntity-method} 5 | \title{ ~~ Methods for Function \code{onWeb} ~~} 6 | \description{ 7 | ~~ Methods for function \code{onWeb} ~~ 8 | } 9 | \section{Methods}{ 10 | \describe{ 11 | 12 | \item{\code{signature(entity = "SynapseEntity")}}{ 13 | open a web browser and navigate to the web page for the Entity 14 | } 15 | 16 | }} 17 | \keyword{methods} 18 | -------------------------------------------------------------------------------- /tools/docGen/asTypedListTemplate.Rd: -------------------------------------------------------------------------------- 1 | \name{TypedList} 2 | ##alias## 3 | \docType{methods} 4 | \title{ 5 | Functions for typed lists 6 | } 7 | \description{Methods for typed lists.} 8 | \usage{ 9 | ##usage## 10 | } 11 | \arguments{ 12 | \item{x}{ 13 | An untyped list or vector. 14 | } 15 | } 16 | \details{ 17 | Returns a typed list for a generic list or vector. 18 | } 19 | \examples{ 20 | untyped<-c("a", "b", "c") 21 | typed<-as.CharacterList(untyped) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /man/getParentEntity-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{getParentEntity-methods} 2 | \docType{methods} 3 | \alias{getParentEntity-methods} 4 | \alias{getParentEntity,SynapseEntity-method} 5 | \title{ ~~ Methods for Function \code{getParentEntity} ~~} 6 | \description{ 7 | ~~ Methods for function \code{getParentEntity} ~~ 8 | } 9 | \section{Methods}{ 10 | \describe{ 11 | 12 | \item{\code{signature(entity = "SynapseEntity")}}{ 13 | Get the parent entity 14 | } 15 | }} 16 | \keyword{methods} 17 | -------------------------------------------------------------------------------- /man/annotationNames.Rd: -------------------------------------------------------------------------------- 1 | \name{annotationNames} 2 | \alias{annotationNames} 3 | \title{ 4 | annotationNames 5 | } 6 | \description{ 7 | Returns the names of the annotations set on a given entity. 8 | } 9 | \usage{ 10 | annotationNames(entity) 11 | } 12 | \arguments{ 13 | \item{entity}{ 14 | The annotated entity. 15 | } 16 | } 17 | 18 | \value{ 19 | A vector of character strings giving the names of the annotations on the entity. 20 | } 21 | \seealso{ 22 | \code{\link{annotValue}} 23 | } -------------------------------------------------------------------------------- /man/getActivity-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{getActivity-methods} 2 | \alias{getActivity} 3 | \title{ 4 | \code{getActivity} 5 | } 6 | \description{ 7 | Function for retrieving the Activity based on its ID 8 | } 9 | \usage{ 10 | getActivity(id) 11 | } 12 | \arguments{ 13 | \item{id}{ 14 | the ID of the Activity 15 | } 16 | } 17 | \details{ 18 | Retrieves an Activity from Synapse based on its ID. 19 | } 20 | \value{ 21 | an Activity object 22 | } 23 | 24 | \author{ 25 | Bruce Hoff 26 | } 27 | -------------------------------------------------------------------------------- /man/properties.Rd: -------------------------------------------------------------------------------- 1 | \name{properties} 2 | \alias{properties} 3 | \alias{propertyValue<-} 4 | \alias{propertyValue} 5 | \alias{propertyValues<-} 6 | \alias{propertyValues} 7 | \alias{deleteProperty} 8 | \title{ 9 | Functions for Manipulating Entity Properties 10 | } 11 | \description{ 12 | Manage object properties 13 | } 14 | \usage{ 15 | properties(object) 16 | } 17 | %- maybe also 'usage' for other objects documented here. 18 | \arguments{ 19 | \item{object}{ 20 | The Synapse object of interest 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /inst/unitTests/test_QueryResult.R: -------------------------------------------------------------------------------- 1 | ## test QueryResult object 2 | ## 3 | ## Author: J. Christopher Bare 4 | ############################################################################### 5 | 6 | unitTestQueryResult_LimitAndOffset <- function() { 7 | qr <- synapseClient:::QueryResult$new('select * from dataset limit 123 offset 456', blockSize=78) 8 | checkEquals(qr$limit, 123) 9 | checkEquals(qr$offset, 456) 10 | checkEquals(qr$blockSize, 78) 11 | checkEquals(qr$queryStatement, 'select * from dataset') 12 | } 13 | 14 | -------------------------------------------------------------------------------- /R/synapseVersionsServiceEndpoint.R: -------------------------------------------------------------------------------- 1 | ## set and get the Synapse Versions service endpoint 2 | ## 3 | ## Author: Bruce Hoff 4 | ############################################################################### 5 | 6 | synapseVersionsServiceEndpoint <- 7 | function(endpoint) 8 | { 9 | if (!missing(endpoint)) { 10 | .setCache("versionsServiceEndpoint", endpoint) 11 | } else { 12 | return(.getCache("versionsServiceEndpoint")) 13 | } 14 | } 15 | 16 | .getVersionsEndpoint <- function() { 17 | .getCache("versionsServiceEndpoint") 18 | } 19 | 20 | -------------------------------------------------------------------------------- /R/jsonListToDataFrame.R: -------------------------------------------------------------------------------- 1 | ## Convert a JSON list to a data.frame 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | .jsonListToDataFrame <- function(jsonList){ 7 | returnVal <- data.frame() 8 | for(i in seq(along=jsonList)){ 9 | thisRow <- .parseSingleRow(jsonList[[i]]) 10 | if(is.null(returnVal)){ 11 | returnVal <- thisRow 12 | }else{ 13 | returnVal <- .rowMerge(returnVal, thisRow) 14 | } 15 | } 16 | return(returnVal) 17 | } 18 | -------------------------------------------------------------------------------- /R/logErrorToSynapse.R: -------------------------------------------------------------------------------- 1 | # Server side logging of exceptions encountered in the client 2 | # 3 | # Author: brucehoff 4 | # 5 | # 6 | ############################################################################### 7 | 8 | logErrorToSynapse<-function(label, message) { 9 | logEntry<-LogEntry(label=label, message=message) 10 | synapsePost("/log", 11 | createListFromS4Object(logEntry), 12 | anonymous = TRUE, 13 | checkHttpStatus=FALSE, 14 | logErrorsToSynapse=FALSE # if an error occurs while logging, don't recursively generate the same error 15 | ) 16 | } 17 | -------------------------------------------------------------------------------- /man/generatedBy.Rd: -------------------------------------------------------------------------------- 1 | \name{generatedBy} 2 | \alias{generatedBy} 3 | \title{ 4 | \code{generatedBy} 5 | } 6 | \description{ 7 | Function for retrieving the Activity which generated an Entity 8 | } 9 | \usage{ 10 | generatedBy(entity) 11 | } 12 | \arguments{ 13 | \item{entity}{ 14 | the entity of interest 15 | } 16 | } 17 | \details{ 18 | This method returns information already in the session. There is no server interaction. 19 | } 20 | \value{ 21 | The Activity which generated the given Entity, or NULL if there is no activity. 22 | } 23 | 24 | \author{ 25 | Bruce Hoff 26 | } 27 | 28 | -------------------------------------------------------------------------------- /R/parseJSONRecords.R: -------------------------------------------------------------------------------- 1 | ## Parse JSON records to a table 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################## 5 | 6 | .parseJSONRecords <- 7 | function(json.list) 8 | { 9 | resultsTable <- data.frame() 10 | for(i in seq_along(json.list)){ 11 | thisRow <- .parseSingleRow(json.list[[i]]) 12 | if(is.null(resultsTable)){ 13 | resultsTable <- thisRow 14 | }else{ 15 | resultsTable <- .rowMerge(resultsTable, thisRow) 16 | } 17 | } 18 | return(resultsTable) 19 | } 20 | -------------------------------------------------------------------------------- /man/synapseCacheDir.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseCacheDir} 2 | \alias{synapseCacheDir} 3 | \title{ 4 | Synapse Local File Cache Directory 5 | } 6 | \description{ 7 | Set and retrieve the local directory path to be used for caching synapse data. 8 | } 9 | \usage{ 10 | synapseCacheDir(cacheDir) 11 | } 12 | \arguments{ 13 | \item{cacheDir}{ 14 | A valid directory path on the local filesystem. 15 | } 16 | } 17 | 18 | \value{ 19 | If called with no arguments, returns the path to the root of the local file cache. 20 | } 21 | \author{ 22 | Matt Furia 23 | } 24 | \seealso{ 25 | \code{\link{synGet}} 26 | } 27 | -------------------------------------------------------------------------------- /R/now.R: -------------------------------------------------------------------------------- 1 | ## get the current time 2 | ## 3 | ## Author: Nicole Deflaxu 4 | ############################################################################### 5 | 6 | # All dates sent to Synapse should be in UTC 7 | .now <- function() { 8 | as.POSIXlt(Sys.time(), 'UTC') 9 | } 10 | 11 | .formatAsISO8601<-function(t) { 12 | format(as.POSIXlt(t, 'UTC', usetz=TRUE), "%Y-%m-%dT%H:%M:%S.000Z") 13 | } 14 | 15 | # All dates sent to Synapse as strings should be formatted as ISO8601 dates in timezone UTC 16 | .nowAsString <- function() { 17 | .formatAsISO8601(Sys.time()) 18 | } -------------------------------------------------------------------------------- /inst/unitTests/test_synToJson.R: -------------------------------------------------------------------------------- 1 | # unit tests for synToJson.R 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | library("rjson") 7 | 8 | unitTest_SynToJsonWithNAs<-function() { 9 | orig<-list(foo="bar", baz=NA, bar=list(a="A",b=NA)) 10 | expected<-list(foo="bar", bar=list(a="A")) 11 | checkEquals(synapseClient:::synToJson(orig), toJSON(expected)) 12 | } 13 | 14 | unitTest_UnnamedElements<-function() { 15 | orig<-list(foo=list("foo", "bar", "baz")) 16 | checkEquals(synapseClient:::synToJson(orig), toJSON(orig)) 17 | } 18 | -------------------------------------------------------------------------------- /man/synGetColumns.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetColumns} 2 | \alias{synGetColumns} 3 | \docType{methods} 4 | \title{ 5 | synGetColumns 6 | } 7 | \description{Get the column objects for a Table, given the Table, TableSchema, or ID} 8 | \usage{synGetColumns(arg)} 9 | \arguments{ 10 | \item{arg}{ 11 | the Table, TableSchema, or ID of the table of interest. 12 | } 13 | } 14 | \value{ 15 | A TableColumnList (a typed list of TableColumn objects) for the columns of the given Table. 16 | } 17 | \seealso{ 18 | \code{\link{TableColumn},\link{synAddColumn},\link{synRemoveColumn},\link{Table},\link{TableSchema}} 19 | } 20 | -------------------------------------------------------------------------------- /R/getParentEntity.R: -------------------------------------------------------------------------------- 1 | ## Method for getting parent entity 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | setMethod( 7 | f = "getParentEntity", 8 | signature = "numeric", 9 | definition = function(entity){ 10 | getParentEntity(as.character(entity)) 11 | } 12 | ) 13 | 14 | setMethod( 15 | f = "getParentEntity", 16 | signature = "character", 17 | definition = function(entity){ 18 | entity <- getEntity(entity) 19 | getEntity(propertyValue(entity, "parentId")) 20 | } 21 | ) 22 | -------------------------------------------------------------------------------- /man/properties-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{properties-methods} 2 | \docType{methods} 3 | \alias{properties-methods} 4 | \alias{properties,SynapseAnnotation-method} 5 | \alias{properties,SynapseEntity-method} 6 | \title{ ~~ Methods for Function \code{properties} ~~} 7 | \description{ 8 | ~~ Methods for function \code{properties} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation")}}{ 14 | get the properties as a list 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity")}}{ 18 | get the properties as a list 19 | } 20 | }} 21 | \keyword{methods} 22 | -------------------------------------------------------------------------------- /man/synGetActivity.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetActivity} 2 | \alias{synGetActivity} 3 | \title{ 4 | \code{synGetActivity} 5 | } 6 | \description{ 7 | Function for retrieving the Activity based on the Entity which it generates 8 | } 9 | \usage{ 10 | synGetActivity(entity) 11 | synGetActivity(entityId) 12 | } 13 | \arguments{ 14 | \item{entity}{ 15 | the entity (or entity Id if the entity) generted by the Activity 16 | } 17 | } 18 | \details{ 19 | Retrieves an Activity from Synapse based on the Entity which it generates. 20 | } 21 | \value{ 22 | an Activity object 23 | } 24 | 25 | \author{ 26 | Bruce Hoff 27 | } 28 | -------------------------------------------------------------------------------- /man/synDelete.Rd: -------------------------------------------------------------------------------- 1 | \name{synDelete} 2 | \alias{synDelete} 3 | \title{ 4 | synDelete 5 | } 6 | \description{ 7 | Delete an object from Synapse 8 | } 9 | \usage{ 10 | synDelete(object) 11 | } 12 | %- maybe also 'usage' for other objects documented here. 13 | \arguments{ 14 | \item{object}{ 15 | One of an Entity, Activity, Evaluation, WikiPage, or Submission. 16 | } 17 | } 18 | \details{ 19 | Deletes the given object from Synapse. 20 | } 21 | 22 | \seealso{ 23 | \code{\link{synStore}} 24 | } 25 | \examples{ 26 | \dontrun{ 27 | evaluation<-synGetEvaluation("123456") 28 | synDelete(evaluation) 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /man/UserProfile.Rd: -------------------------------------------------------------------------------- 1 | \name{UserProfile} 2 | \alias{UserProfile} 3 | \docType{methods} 4 | \title{ 5 | Constructor for UserProfile 6 | } 7 | \description{ 8 | Constructor for UserProfile 9 | } 10 | \usage{UserProfile()} 11 | \details{ 12 | This constructor is not called directly, rather an instance is returned by synGetUserProfile(principalId). 13 | } 14 | \examples{ 15 | \dontrun{ 16 | # get my own user profile 17 | profile<-synGetUserProfile() 18 | # get someone else's profile 19 | principalId<-"123456" 20 | profile<-synGetUserProfile(principalId) 21 | } 22 | } 23 | \seealso{ 24 | \code{\link{synGetUserProfile}} 25 | } 26 | -------------------------------------------------------------------------------- /man/propertyNames.Rd: -------------------------------------------------------------------------------- 1 | \name{propertyNames} 2 | \alias{propertyNames} 3 | \title{ 4 | propertyNames 5 | } 6 | \description{ 7 | Returns the names of the properties defined for a given Synapse object. 8 | } 9 | \usage{ 10 | propertyNames(object) 11 | } 12 | \arguments{ 13 | \item{entity}{ 14 | The Synapse object of interest. 15 | } 16 | } 17 | \value{ 18 | A vector of character strings giving the names of the properties defined for a given Synapse object. 19 | } 20 | \examples{ 21 | propertyNames(File(parentId="syn101")) 22 | propertyNames(Evaluation()) 23 | } 24 | \seealso{ 25 | \code{\link{propertyValue}} 26 | } 27 | 28 | -------------------------------------------------------------------------------- /man/propertyValues-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{propertyValues-methods} 2 | \docType{methods} 3 | \alias{propertyValues-methods} 4 | \alias{propertyValues,SynapseAnnotation-method} 5 | \alias{propertyValues,SynapseEntity-method} 6 | \title{ ~~ Methods for Function \code{propertyValues} ~~} 7 | \description{ 8 | ~~ Methods for function \code{propertyValues} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation")}}{ 14 | Get the property values as a list 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity")}}{ 18 | Get the property values as a list 19 | } 20 | }} 21 | -------------------------------------------------------------------------------- /R/synFromJson.R: -------------------------------------------------------------------------------- 1 | # synFromJson: translates JSON returned from Synapse web requests into list objects 2 | # 3 | # Author: bhoff 4 | ############################################################################### 5 | 6 | 7 | 8 | synFromJson<-function(content) { 9 | # fromJSON(content, method="R", unexpected.escape="skip") 10 | result<-try(fromJSON(content, method="R", unexpected.escape="skip"), silent=TRUE) 11 | if (class(result)=="try-error") { 12 | cleanedContent<-gsub("\\/", "/", content, fixed=TRUE) 13 | fromJSON(cleanedContent, method="R", unexpected.escape="skip") 14 | } else { 15 | result 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /man/generatedBy_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{generatedBy<--methods} 2 | \alias{generatedBy<-} 3 | \title{ 4 | \code{generatedBy<-} 5 | } 6 | \description{ 7 | Method for setting the Activity which generated an Entity 8 | } 9 | \usage{ 10 | generatedBy(entity)<-activity 11 | } 12 | \arguments{ 13 | \item{entity}{ 14 | the entity of interest 15 | } 16 | \item{activity}{ 17 | the activity which generated the entity 18 | } 19 | } 20 | \details{ 21 | Sets the Activity which generated an entity. NULL is allowed. No server interaction takes place. (That is done when \code{storeEntity} is called.) 22 | } 23 | 24 | \author{ 25 | Bruce Hoff 26 | } -------------------------------------------------------------------------------- /man/TableSchema.Rd: -------------------------------------------------------------------------------- 1 | \name{TableSchema} 2 | \alias{TableSchema} 3 | \docType{methods} 4 | \title{ 5 | TableSchema Constructor 6 | } 7 | \description{Constructor for TableSchema} 8 | \usage{TableSchema(name, parent, columns, ...)} 9 | \arguments{ 10 | \item{name}{ 11 | the name of the new table schema 12 | } 13 | \item{parent}{ 14 | the parent entity (either its ID or the entity itself) 15 | } 16 | \item{columns}{ 17 | a list or vector of the IDs of the columns to be included in the table schema, or of the column objects themselves 18 | } 19 | } 20 | 21 | \seealso{ 22 | \code{\link{synStore},\link{synGet}} 23 | } 24 | -------------------------------------------------------------------------------- /man/getFileLocation.Rd: -------------------------------------------------------------------------------- 1 | \name{getFileLocation} 2 | \alias{getFileLocation} 3 | \title{ 4 | getFileLocation 5 | } 6 | \description{ 7 | function to get the location of the attachment to a File 8 | } 9 | \usage{getFileLocation(fileObject)} 10 | \details{ 11 | Returns a string which is the path to the file attached to a File object. 12 | If the File 'links' to an external URL (not downloaded to the local file system), returns the URL itself. 13 | } 14 | \examples{ 15 | \dontrun{ 16 | file<-synGet("syn123456") 17 | filePath<-getFileLocation(file) 18 | } 19 | } 20 | \seealso{ 21 | \code{\link{File}} 22 | \code{\link{synGet}} 23 | \code{\link{synStore}} 24 | } -------------------------------------------------------------------------------- /man/propertyValue-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{propertyValue-methods} 2 | \docType{methods} 3 | \alias{propertyValue-methods} 4 | \alias{propertyValue,SynapseAnnotation,character-method} 5 | \alias{propertyValue,SynapseEntity,character-method} 6 | \title{ ~~ Methods for Function \code{propertyValue} ~~} 7 | \description{ 8 | ~~ Methods for function \code{propertyValue} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation", which = "character")}}{ 14 | get the property value 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity", which = "character")}}{ 18 | get the property value 19 | } 20 | }} 21 | -------------------------------------------------------------------------------- /R/parseSingleRow.R: -------------------------------------------------------------------------------- 1 | ## Parse a single row from a JSON list 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################## 5 | 6 | .parseSingleRow <- 7 | function(row) 8 | { 9 | ## constants 10 | kNaValue <- NA 11 | kMultiValueDelimiterString <- ', ' 12 | ## end constants 13 | 14 | ## iterate through rownames and add each element to the data frame 15 | isNull <- sapply(row,is.null) 16 | row[isNull] <- kNaValue 17 | row[!isNull] <- lapply(row[!isNull], paste, collapse=kMultiValueDelimiterString) 18 | data.frame(row, stringsAsFactors=FALSE) 19 | } 20 | -------------------------------------------------------------------------------- /man/annotationValues-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{annotationValues-methods} 2 | \docType{methods} 3 | \alias{annotationValues-methods} 4 | \alias{annotationValues,SynapseAnnotation-method} 5 | \alias{annotationValues,SynapseEntity-method} 6 | \title{ ~~ Methods for Function \code{annotationValues} ~~} 7 | \description{ 8 | ~~ Methods for function \code{annotationValues} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation")}}{ 14 | get the annotations as a list 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity")}}{ 18 | get the annotations as a list 19 | 20 | } 21 | }} 22 | \keyword{methods} 23 | -------------------------------------------------------------------------------- /man/propertyValues_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{propertyValues<--methods} 2 | \docType{methods} 3 | \alias{propertyValues<--methods} 4 | \alias{propertyValues<-,SynapseAnnotation,list-method} 5 | \alias{propertyValues<-,SynapseEntity,list-method} 6 | \title{ ~~ Methods for Function \code{propertyValues<-} ~~} 7 | \description{ 8 | ~~ Methods for function \code{propertyValues<-} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation", value = "list")}}{ 14 | set the property values 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity", value = "list")}}{ 18 | set the property values 19 | } 20 | }} 21 | -------------------------------------------------------------------------------- /man/synAddColumn.Rd: -------------------------------------------------------------------------------- 1 | \name{synAddColumn} 2 | \alias{synAddColumn} 3 | \docType{methods} 4 | \title{ 5 | synAddColumn 6 | } 7 | \description{Add a column to a Table Schema} 8 | \usage{synAddColumn(arg, column)} 9 | \arguments{ 10 | \item{arg}{ 11 | the Table, TableSchema, or ID of the table of interest. 12 | } 13 | \item{column}{ 14 | the TableColumn or column ID to add to the table. 15 | } 16 | } 17 | \details{ 18 | Note: No server interaction takes place. (That is done when \code{synStore} is called.) 19 | } 20 | \seealso{ 21 | \code{\link{TableColumn},\link{synGetColumn},\link{synAddColumn},\link{Table},\link{TableSchema},\link{synStore}} 22 | } 23 | -------------------------------------------------------------------------------- /man/synGetWiki.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetWiki} 2 | \alias{synGetWiki} 3 | \title{ 4 | synGetWiki 5 | } 6 | \description{ 7 | Function to retrieve a Wiki Page. 8 | } 9 | \usage{ 10 | synGetWiki(owner) 11 | synGetWiki(owner, id) 12 | } 13 | \details{ 14 | Retrieves a WikiPage given its owner (Entity or Evaluation) and, optionally, its ID. If no ID is specified then 15 | the root ID is returned. To get the IDs of all the WikiPages for an owner, see synGetWikiHeaders. 16 | } 17 | \examples{ 18 | \dontrun{ 19 | entity<-synGet("syn123456") 20 | wikiPage<-synGetWiki(entity) 21 | } 22 | } 23 | \seealso{ 24 | \code{\link{synGetWikiHeaders}} 25 | \code{\link{synStore}} 26 | } 27 | -------------------------------------------------------------------------------- /man/used.Rd: -------------------------------------------------------------------------------- 1 | \name{used} 2 | \alias{used} 3 | \title{ 4 | \code{used} 5 | } 6 | \description{ 7 | Function for getting the entities used to generate an Entity or Activity 8 | } 9 | \usage{ 10 | used(entity) 11 | used(activity) 12 | activity$used 13 | } 14 | \arguments{ 15 | \item{entity}{ 16 | The entity/activity of interest. 17 | } 18 | } 19 | \details{ 20 | This method returns information already in the session. There is no server interaction. 21 | } 22 | \value{ 23 | A list of entities involved in generating the given entity/activity, but not "executed". (See also \code{executed(entity)}.) 24 | } 25 | 26 | \author{ 27 | Bruce Hoff 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/R_init_Synapse.c: -------------------------------------------------------------------------------- 1 | /* Initialize c functions for curl writer in R 2 | * 3 | * Author: Martin Morgan 4 | */ 5 | #include 6 | #include 7 | #include "synapse_curl.h" 8 | 9 | static const R_CallMethodDef callMethods[] = { 10 | {".writer_open", (DL_FUNC) &writer_open, 1}, 11 | {".writer_close", (DL_FUNC) &writer_close, 1}, 12 | {NULL, NULL, 0} 13 | }; 14 | 15 | void 16 | R_init_Synapse(DllInfo *info) 17 | { 18 | R_registerRoutines(info, NULL, callMethods, NULL, NULL); 19 | } 20 | 21 | void 22 | R_unload_Synapse(DllInfo *info) 23 | { 24 | /* any clean-up when package unloaded */ 25 | } 26 | -------------------------------------------------------------------------------- /R/refreshSessionToken.R: -------------------------------------------------------------------------------- 1 | ## Refresh the synapse session token 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################## 5 | 6 | synapseRefreshSessionToken <- 7 | function(sessionToken, host=getEndpointLocationForService("AUTH")) 8 | { 9 | # constants 10 | kService <- "/session" 11 | ## end constants 12 | 13 | entity <- list() 14 | entity$sessionToken <- sessionToken 15 | 16 | uri <- kService 17 | response <- synapsePut(uri=uri, entity=entity, endpoint=synapseServiceEndpoint("AUTH"), anonymous=TRUE) 18 | .setCache("sessionTimestamp", Sys.time()) 19 | } 20 | -------------------------------------------------------------------------------- /inst/unitTests/test_checkLatestVersion.R: -------------------------------------------------------------------------------- 1 | # Unit tests for blacklist checking logic 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | 8 | unitTestMajorVersion <- function() { 9 | checkEquals("0.10", synapseClient:::.majorVersion("0.10")) 10 | checkEquals("0.10", synapseClient:::.majorVersion("0.10-1")) 11 | checkEquals("1.0", synapseClient:::.majorVersion("1.0-0")) 12 | checkTrue(synapseClient:::.majorVersionDiff("1.0-1", "1.1-1")) 13 | checkTrue(!synapseClient:::.majorVersionDiff("1.0-1", "1.0")) 14 | checkTrue(!synapseClient:::.majorVersionDiff("1.0-1", "1.0-2")) 15 | } 16 | 17 | -------------------------------------------------------------------------------- /man/annotValue-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{annotValue-methods} 2 | \docType{methods} 3 | \alias{annotValue-methods} 4 | \alias{annotValue,SynapseAnnotation,character-method} 5 | \alias{annotValue,SynapseEntity,character-method} 6 | \title{Methods for Function \code{annotValue}} 7 | \description{ 8 | Methods for function \code{annotValue} 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation", which = "character")}}{ 14 | get the annotation specified by which 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity", which = "character")}}{ 18 | get the annotation specified by which 19 | } 20 | }} 21 | \keyword{methods} 22 | -------------------------------------------------------------------------------- /man/synapseClient-package.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseClient-package} 2 | \alias{synapseClient-package} 3 | \alias{synapseClient} 4 | \docType{package} 5 | \title{ 6 | Synapse Client 7 | } 8 | \description{ 9 | A client for interacting with the Synapse web services. 10 | } 11 | \details{ 12 | \tabular{ll}{ 13 | Package: \tab synapseClient\cr 14 | Type: \tab Package\cr 15 | Version: \tab 1.15-3\cr 16 | Date: \tab 2017-12-08\cr 17 | License: \tab GPL\cr 18 | LazyLoad: \tab yes\cr 19 | } 20 | } 21 | \author{ 22 | Matt Furia and Nicole Deflaux 23 | Maintainer: Bruce Hoff 24 | } 25 | \keyword{ package } 26 | \examples{ 27 | ## Not Run 28 | 29 | ## End Not Run 30 | } 31 | -------------------------------------------------------------------------------- /R/synapseResetEndpoints.R: -------------------------------------------------------------------------------- 1 | ## reset synapse endpoints to their default values 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseResetEndpoints <- 7 | function() 8 | { 9 | synapseAuthServiceEndpoint("https://auth-prod.prod.sagebase.org/auth/v1") 10 | synapseRepoServiceEndpoint("https://repo-prod.prod.sagebase.org/repo/v1") 11 | synapseFileServiceEndpoint("https://file-prod.prod.sagebase.org/file/v1") 12 | synapseVersionsServiceEndpoint("http://versions.synapse.sagebase.org/synapseRClient") 13 | synapsePortalEndpoint("http://synapse.sagebase.org") 14 | } 15 | -------------------------------------------------------------------------------- /man/synDeleteEntityACL.Rd: -------------------------------------------------------------------------------- 1 | \name{Delete Entity Access Control List} 2 | \alias{synDeleteEntityACL} 3 | \docType{methods} 4 | \title{ 5 | Delete Entity Access Control List 6 | } 7 | 8 | \description{ 9 | Deletes the ACL for an entity, forcing it to inherit the sharing settings of its parent. 10 | } 11 | \usage{synDeleteEntityACL(id)} 12 | \arguments{ 13 | \item{id}{ 14 | The ID of the entity whose ACL is to be delete. 15 | } 16 | } 17 | 18 | \seealso{ 19 | \code{\link{synCreateEntityACL}} 20 | \code{\link{synGetEntityACL}} 21 | \code{\link{synUpdateEntityACL}} 22 | \code{\link{AccessControlList}} 23 | \code{\link{ResourceAccessList}} 24 | \code{\link{ResourceAccess}} 25 | } 26 | -------------------------------------------------------------------------------- /R/TableColumn.R: -------------------------------------------------------------------------------- 1 | # methods relating to the TableColumn class 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | setMethod( 8 | f = "synStore", 9 | signature = "TableColumn", 10 | definition = function(entity) { 11 | if (length(entity$id)==0) { 12 | # create 13 | createS4Object(entity, "/column") 14 | } else { 15 | stop("Cannot update an existing TableColumn.") 16 | } 17 | } 18 | ) 19 | 20 | synGetColumn<-function(id) { 21 | listResult<-synRestGET(sprintf("/column/%s", id)) 22 | objectResult<-createS4ObjectFromList(listResult, "TableColumn") 23 | } 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /man/synRemoveColumn.Rd: -------------------------------------------------------------------------------- 1 | \name{synRemoveColumn} 2 | \alias{synRemoveColumn} 3 | \docType{methods} 4 | \title{ 5 | synRemoveColumn 6 | } 7 | \description{Remove a column from a Table Schema} 8 | \usage{synRemoveColumn(arg, column)} 9 | \arguments{ 10 | \item{arg}{ 11 | the Table, TableSchema, or ID of the table of interest. 12 | } 13 | \item{column}{ 14 | the TableColumn or column ID to remove from the table. 15 | } 16 | } 17 | \details{ 18 | Note: No server interaction takes place. (That is done when \code{synStore} is called.) 19 | } 20 | \seealso{ 21 | \code{\link{TableColumn},\link{synGetColumn},\link{synRemoveColumn},\link{Table},\link{TableSchema},\link{synStore}} 22 | } 23 | -------------------------------------------------------------------------------- /man/executed.Rd: -------------------------------------------------------------------------------- 1 | \name{executed} 2 | \alias{executed} 3 | \title{ 4 | \code{executed} 5 | } 6 | \description{ 7 | Function for getting the entities executed to generate an Entity or Activity 8 | } 9 | \usage{ 10 | executed(entity) 11 | executed(activity) 12 | activity$executed 13 | } 14 | \arguments{ 15 | \item{entity}{ 16 | The entity/activity of interest. 17 | } 18 | } 19 | \details{ 20 | This method returns information already in the session. There is no server interaction. 21 | } 22 | \value{ 23 | A list of entities involved in generating the given entity/activity, but only if "executed". (See also \code{used(entity)}.) 24 | } 25 | 26 | \author{ 27 | Bruce Hoff 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /man/deleteProperty-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{deleteProperty-methods} 2 | \docType{methods} 3 | \alias{deleteProperty-methods} 4 | \alias{deleteProperty,SynapseAnnotation,character-method} 5 | \alias{deleteProperty,SynapseEntity,character-method} 6 | \title{ ~~ Methods for Function \code{deleteProperty} ~~} 7 | \description{ 8 | ~~ Methods for function \code{deleteProperty} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation", which = "character")}}{ 14 | Delete the specified property 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity", which = "character")}}{ 18 | Delete the specified property 19 | } 20 | }} 21 | \keyword{methods} 22 | -------------------------------------------------------------------------------- /inst/resources/test/org/sagebionetworks/test/Test.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Test", 3 | "description": "This is a test entity definition", 4 | "type": "interface", 5 | "properties": { 6 | "string": { 7 | "type": "string", 8 | "description": "string property", 9 | "title": "Name" 10 | }, 11 | "integer": { 12 | "type": "integer", 13 | "description": "integer property", 14 | "title": "Name" 15 | }, 16 | "numeric": { 17 | "type": "numeric", 18 | "description": "numeric property", 19 | "title": "Name" 20 | }, 21 | "transient": { 22 | "type": "string", 23 | "description": "transient string", 24 | "transient": true 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /man/SubmissionStatus.Rd: -------------------------------------------------------------------------------- 1 | \name{SubmissionStatus} 2 | \alias{SubmissionStatus} 3 | \docType{methods} 4 | \title{ 5 | Constructor for SubmissionStatus 6 | } 7 | \description{ 8 | Constructor for SubmissionStatus 9 | } 10 | \usage{SubmissionStatus()} 11 | \details{ 12 | This constructor is not called directly, rather an instance is returned by synGetSubmissionStatus(id), where id is the ID of a Submission. 13 | } 14 | 15 | \examples{ 16 | \dontrun{ 17 | status<-synGetSubmissionStatus("12345") 18 | propertyValue(status, "STATUS")<-"SCORED" 19 | status<-synStore(status) 20 | } 21 | } 22 | \seealso{ 23 | \code{\link{synGetSubmissions}} 24 | \code{\link{synGetSubmissionStatus}} 25 | \code{\link{synStore}} 26 | } 27 | -------------------------------------------------------------------------------- /R/defineS4MethodsForAutogenClasses.R: -------------------------------------------------------------------------------- 1 | # Define constructors and accessors for autogenerated classes 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | s4ClassesToAutoGenerate<-read.table( 7 | system.file("resources/s4ClassesToGenerate.txt",package="synapseClient"), 8 | header=TRUE, colClasses=c("character", "character", "logical")) 9 | 10 | for(i in 1:(dim(s4ClassesToAutoGenerate)[1])) { 11 | className<-s4ClassesToAutoGenerate[i,"className"] 12 | schemaName<-s4ClassesToAutoGenerate[i,"schemaName"] 13 | if (!isVirtual(readEntityDef(schemaName, getSchemaPath()))) { 14 | defineS4ConstructorAndAccessors(className) 15 | } 16 | } -------------------------------------------------------------------------------- /man/deleteAnnotation-methods.Rd: -------------------------------------------------------------------------------- 1 | \name{deleteAnnotation-methods} 2 | \docType{methods} 3 | \alias{deleteAnnotation-methods} 4 | \alias{deleteAnnotation,SynapseAnnotation,character-method} 5 | \alias{deleteAnnotation,SynapseEntity,character-method} 6 | \title{ ~~ Methods for Function \code{deleteAnnotation} ~~} 7 | \description{ 8 | ~~ Methods for function \code{deleteAnnotation} ~~ 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(object = "SynapseAnnotation", which = "character")}}{ 14 | Delete the annotations specified by "which" 15 | } 16 | 17 | \item{\code{signature(object = "SynapseEntity", which = "character")}}{ 18 | Delete the annotations specified by "which" 19 | } 20 | }} 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | src-* 2 | src/*.o 3 | src/*.so 4 | .project 5 | .settings/* 6 | .Rproj.user 7 | .Rbuildignore 8 | rSynapseClient.Rproj 9 | man/AccessControlList.Rd 10 | man/ResourceAccess.Rd 11 | man/Row.Rd 12 | man/RowReference.Rd 13 | man/RowReferenceSet.Rd 14 | man/Settings.Rd 15 | man/TableColumn.Rd 16 | man/TableRowSet.Rd 17 | man/TypedList.Rd 18 | man/asTypedList.Rd 19 | man/AsynchUploadToTableRequestBody.Rd 20 | man/AsynchUploadToTableResponseBody.Rd 21 | man/AsynchronousJobStatus.Rd 22 | man/AsynchronousRequestBody.Rd 23 | man/AsynchronousResponseBody.Rd 24 | man/ExternalUploadDestination.Rd 25 | man/S3UploadDestination.Rd 26 | man/UploadDestination.Rd 27 | man/SubmissionQuota.Rd 28 | inst/resources 29 | .DS_Store 30 | -------------------------------------------------------------------------------- /R/deleteEntity.R: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Author: mfuria 4 | ############################################################################### 5 | 6 | setMethod( 7 | f = "deleteEntity", 8 | signature = "numeric", 9 | definition = function(entity) { 10 | deleteEntity(as.character(entity)) 11 | } 12 | ) 13 | 14 | setMethod( 15 | f = "deleteEntity", 16 | signature = "character", 17 | definition = function(entity) { 18 | if (isSynapseId(entity)) { 19 | # deleteEntitySFTPAttachments(entity) reenable once SYNR-850 is addressed 20 | synapseDelete(.generateEntityUri(entity)) 21 | } else { 22 | stop(sprintf("%s is not a Synapse Id.", entity[1])) 23 | } 24 | } 25 | ) 26 | 27 | -------------------------------------------------------------------------------- /R/getServerVersion.R: -------------------------------------------------------------------------------- 1 | # 2 | # returns the version of the Synapse server 3 | # 4 | getServerVersion<-function(logErrorsToSynapse=TRUE) { 5 | cacheTimestampName<-"serverVersionTimestamp" 6 | cacheVersionInfoName<-"serverVersion" 7 | cacheRefreshSeconds<-300 # 5 minutes 8 | now<-Sys.time() 9 | cacheTimestamp<-.getCache(cacheTimestampName) 10 | versionInfo<-.getCache(cacheVersionInfoName) 11 | if (is.null(versionInfo) || is.null(cacheTimestamp) || now-cacheTimestamp>cacheRefreshSeconds) { 12 | versionInfo<-synapseGet("/version", anonymous=T, logErrorsToSynapse=logErrorsToSynapse)$version 13 | .setCache(cacheTimestampName, now) 14 | .setCache(cacheVersionInfoName, versionInfo) 15 | } 16 | versionInfo 17 | } 18 | -------------------------------------------------------------------------------- /man/synAnnot.Rd: -------------------------------------------------------------------------------- 1 | \name{synAnnot} 2 | \alias{synAnnot} 3 | \title{ 4 | synAnnot 5 | } 6 | \description{ 7 | Get/set properties/annotations on a Synapse Entity 8 | } 9 | \usage{ 10 | synAnnot(entity, attribute)<-value 11 | synAnnot(entity, attribute) 12 | } 13 | %- maybe also 'usage' for other objects documented here. 14 | \arguments{ 15 | \item{entity}{ 16 | The entity whose properties/annotations are to be set/retrieved. 17 | } 18 | \item{attribute}{ 19 | The name of the property or value to be set/retrieved. 20 | } 21 | } 22 | \value{ 23 | The attribute value. 24 | } 25 | \examples{ 26 | \dontrun{ 27 | synAnnot(entity, "name")<-"syn101" 28 | synAnnot(entity, "tissueType")<-"plasma" 29 | synAnnot(entity, "id") 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /man/synGetProperty.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetProperty} 2 | \alias{synGetProperty} 3 | \docType{methods} 4 | \title{ 5 | synGetProperty 6 | } 7 | \description{ 8 | Get a property for an entity. 9 | } 10 | \usage{synGetProperty(entity, name)} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity for which to get the property. 14 | } 15 | \item{name}{ 16 | The name of the property to get. 17 | } 18 | } 19 | \value{ 20 | The property value for the given property name. 21 | } 22 | \seealso{ 23 | \code{\link{synGetAnnotations}} 24 | \code{\link{synSetAnnotations}} 25 | \code{\link{synGetProperties}} 26 | \code{\link{synSetProperties}} 27 | \code{\link{synGetAnnotation}} 28 | \code{\link{synSetAnnotation}} 29 | \code{\link{synSetProperty}} 30 | } 31 | -------------------------------------------------------------------------------- /man/synSetProperty.Rd: -------------------------------------------------------------------------------- 1 | \name{synSetProperty} 2 | \alias{synSetProperty} 3 | \docType{methods} 4 | \title{ 5 | synSetProperty 6 | } 7 | \description{ 8 | Set a property on an entity. 9 | } 10 | \usage{synSetProperty(entity, name)<-value} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity on which to set the property. 14 | } 15 | \item{name}{ 16 | The name of the property to set. 17 | } 18 | \item{value}{ 19 | The value of the property to set. 20 | } 21 | } 22 | \seealso{ 23 | \code{\link{synGetAnnotations}} 24 | \code{\link{synSetAnnotations}} 25 | \code{\link{synGetProperties}} 26 | \code{\link{synSetProperties}} 27 | \code{\link{synGetAnnotation}} 28 | \code{\link{synSetAnnotation}} 29 | \code{\link{synGetProperty}} 30 | } 31 | -------------------------------------------------------------------------------- /man/synGetProperties.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetProperties} 2 | \alias{synGetProperties} 3 | \docType{methods} 4 | \title{ 5 | synGetProperties 6 | } 7 | \description{ 8 | Get all the properties for an entity. 9 | } 10 | \usage{synGetProperties(entity)} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity for which to get the properties. 14 | } 15 | } 16 | \value{ 17 | A named list in which the names are the entity's property names and the values are the corresponding values. 18 | } 19 | \seealso{ 20 | \code{\link{synGetAnnotations}} 21 | \code{\link{synSetAnnotations}} 22 | \code{\link{synSetProperties}} 23 | \code{\link{synGetAnnotation}} 24 | \code{\link{synSetAnnotation}} 25 | \code{\link{synGetProperty}} 26 | \code{\link{synSetProperty}} 27 | } 28 | -------------------------------------------------------------------------------- /man/synSetProperties.Rd: -------------------------------------------------------------------------------- 1 | \name{synSetProperties} 2 | \alias{synSetProperties} 3 | \docType{methods} 4 | \title{ 5 | synSetProperties 6 | } 7 | \description{ 8 | Set all the properties on an entity. 9 | } 10 | \usage{synSetProperties(entity)<-values} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity on which to set the properties. 14 | } 15 | \item{values}{ 16 | A named list in which the names are the property names and the values are the property values. 17 | } 18 | } 19 | \seealso{ 20 | \code{\link{synGetAnnotations}} 21 | \code{\link{synSetAnnotations}} 22 | \code{\link{synGetProperties}} 23 | \code{\link{synGetAnnotation}} 24 | \code{\link{synSetAnnotation}} 25 | \code{\link{synGetProperty}} 26 | \code{\link{synSetProperty}} 27 | } 28 | -------------------------------------------------------------------------------- /R/AAAGlobalCache.R: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Author: furia 4 | ############################################################################### 5 | 6 | 7 | ## package-local 'getter' 8 | .getCache <- 9 | function(key) 10 | { 11 | cache <- new("GlobalCache") 12 | cache@env[[key]] 13 | } 14 | 15 | ## package-local 'setter' 16 | .setCache <- 17 | function(key, value) 18 | { 19 | cache <- new("GlobalCache") 20 | cache@env[[key]] <- value 21 | } 22 | 23 | .deleteCache <- 24 | function(keys) 25 | { 26 | cache <- new("GlobalCache") 27 | indx <- which(keys %in% objects(cache@env)) 28 | if(length(indx) > 0) 29 | rm(list=keys[indx], envir=cache@env) 30 | } 31 | 32 | as.environment.GlobalCache <- 33 | function(x) 34 | { 35 | x@env 36 | } 37 | -------------------------------------------------------------------------------- /inst/integrationTests/test_getMimeTypeForFile.R: -------------------------------------------------------------------------------- 1 | integrationTestGetEntityByIdExistingFileCache <- 2 | function() 3 | { 4 | checkEquals("image/jpeg", synapseClient:::getMimeTypeForFile("foo.jpg")) 5 | checkEquals("image/jpeg", synapseClient:::getMimeTypeForFile("foo.jpeg")) 6 | checkEquals("text/html", synapseClient:::getMimeTypeForFile("this.is.a.file.html")) 7 | checkEquals("application/octet-stream", synapseClient:::getMimeTypeForFile("FileWithoutExtension")) 8 | checkEquals("application/octet-stream", synapseClient:::getMimeTypeForFile("foo.unrecognizedExtenion")) 9 | checkEquals("text/x-r", synapseClient:::getMimeTypeForFile("python-copycat.R")) 10 | checkEquals("text/x-r", synapseClient:::getMimeTypeForFile("PYTHON-COPYCAT.r")) 11 | } -------------------------------------------------------------------------------- /man/synGetAnnotations.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetAnnotations} 2 | \alias{synGetAnnotations} 3 | \docType{methods} 4 | \title{ 5 | synGetAnnotations 6 | } 7 | \description{ 8 | Get all the annotations for an entity. 9 | } 10 | \usage{synGetAnnotations(entity)} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity for which to get the annotations. 14 | } 15 | } 16 | \value{ 17 | A named list in which the names are the entity's annotation names and the values are the corresponding values. 18 | } 19 | \seealso{ 20 | \code{\link{synSetAnnotations}} 21 | \code{\link{synGetProperties}} 22 | \code{\link{synSetProperties}} 23 | \code{\link{synGetAnnotation}} 24 | \code{\link{synSetAnnotation}} 25 | \code{\link{synGetProperty}} 26 | \code{\link{synSetProperty}} 27 | } 28 | -------------------------------------------------------------------------------- /man/synGetAnnotation.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetAnnotation} 2 | \alias{synGetAnnotation} 3 | \docType{methods} 4 | \title{ 5 | synGetAnnotation 6 | } 7 | \description{ 8 | Get an annotation for an entity. 9 | } 10 | \usage{synGetAnnotation(entity, name)} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity for which to get the annotation. 14 | } 15 | \item{name}{ 16 | The name of the annotation to get. 17 | } 18 | } 19 | \value{ 20 | The annotation value for the given annotation name. 21 | } 22 | \seealso{ 23 | \code{\link{synGetAnnotations}} 24 | \code{\link{synSetAnnotations}} 25 | \code{\link{synGetProperties}} 26 | \code{\link{synSetProperties}} 27 | \code{\link{synSetAnnotation}} 28 | \code{\link{synGetProperty}} 29 | \code{\link{synSetProperty}} 30 | } 31 | -------------------------------------------------------------------------------- /man/synGetWikiHeaders.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetWikiHeaders} 2 | \alias{synGetWikiHeaders} 3 | \title{ 4 | synGetWikiHeaders 5 | } 6 | \description{ 7 | Function to retrieve the headers of all the Wiki pages belonging to an owner. 8 | } 9 | \usage{ 10 | synGetWikiHeaders(owner) 11 | } 12 | \details{ 13 | Retrieves a list of WikiHeader objects given an owner (Entity or Evaluation). 14 | WikiHeader includes the Wiki's ID and that of its parent Wiki. This information is 15 | necessary to know the tree structure of the Wiki pages belonging to a given owner. 16 | } 17 | \examples{ 18 | \dontrun{ 19 | entity<-synGet("syn123456") 20 | wikiHeaders<-synGetWikiHeaders(entity) 21 | } 22 | } 23 | \seealso{ 24 | \code{\link{synGetWiki}} 25 | \code{\link{WikiHeader}} 26 | } 27 | -------------------------------------------------------------------------------- /man/synSetAnnotation.Rd: -------------------------------------------------------------------------------- 1 | \name{synSetAnnotation} 2 | \alias{synSetAnnotation} 3 | \docType{methods} 4 | \title{ 5 | synSetAnnotation 6 | } 7 | \description{ 8 | Set an annotation on an entity. 9 | } 10 | \usage{synSetAnnotation(entity, name)<-value} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity on which to set the annotation. 14 | } 15 | \item{name}{ 16 | The name of the annotation to set. 17 | } 18 | \item{value}{ 19 | The value of the annotation to set. 20 | } 21 | } 22 | \seealso{ 23 | \code{\link{synGetAnnotations}} 24 | \code{\link{synSetAnnotations}} 25 | \code{\link{synGetProperties}} 26 | \code{\link{synSetProperties}} 27 | \code{\link{synGetAnnotation}} 28 | \code{\link{synGetProperty}} 29 | \code{\link{synSetProperty}} 30 | } 31 | -------------------------------------------------------------------------------- /man/synSetEndpoints.Rd: -------------------------------------------------------------------------------- 1 | \name{synSetEndpoints} 2 | \alias{synSetEndpoints} 3 | \title{ 4 | synSetEndpoints 5 | } 6 | 7 | \usage{ 8 | synSetEndpoints() 9 | synSetEndpoints(repoEndpoint, authEndpoint, fileEndpoint, portalEndpoint) 10 | } 11 | \arguments{ 12 | \item{repoEndpoint}{ 13 | The repository services endpoint. 14 | } 15 | \item{authEndpoint}{ 16 | The authentication services endpoint. 17 | } 18 | \item{fileEndpoint}{ 19 | The file services endpoint. 20 | } 21 | \item{portalEndpoint}{ 22 | The portal (web client) endpoint. 23 | } 24 | 25 | } 26 | \details{ 27 | If called with no arguments, sets to the default values. Otherwise, set the endpoints to the values provided. 28 | } 29 | \seealso{ 30 | \code{\link{synGetEndpoints}} 31 | } 32 | -------------------------------------------------------------------------------- /man/synCreateEntityACL.Rd: -------------------------------------------------------------------------------- 1 | \name{Create Entity Access Control List} 2 | \alias{synCreateEntityACL} 3 | \docType{methods} 4 | \title{ 5 | Create Entity Access Control List 6 | } 7 | 8 | \description{ 9 | Creates an ACL for an entity (e.g. File, Folder, Table), overriding ACL inheritance. 10 | } 11 | \usage{synCreateEntityACL(acl)} 12 | \arguments{ 13 | \item{acl}{ 14 | The AccessControlList to create. The ID field is that of the entity which is to have the ACL. 15 | } 16 | } 17 | \value{ 18 | The created ACL. 19 | } 20 | 21 | \seealso{ 22 | \code{\link{synGetEntityACL}} 23 | \code{\link{synUpdateEntityACL}} 24 | \code{\link{synDeleteEntityACL}} 25 | \code{\link{AccessControlList}} 26 | \code{\link{ResourceAccessList}} 27 | \code{\link{ResourceAccess}} 28 | } 29 | -------------------------------------------------------------------------------- /R/getReference.R: -------------------------------------------------------------------------------- 1 | # 2 | # Methods to return a Reference (an id and verion) given an Entity or Entity ID 3 | # In the latter case there is no version information in the Reference. 4 | # 5 | 6 | 7 | setMethod( 8 | f="getReference", 9 | signature = signature("Entity"), 10 | definition = function(entity) { 11 | versionNumber <- propertyValue(entity, "versionNumber") 12 | if (is.null(versionNumber)) { 13 | list(targetId=propertyValue(entity, "id")) 14 | } else { 15 | list(targetId=propertyValue(entity, "id"), targetVersionNumber=versionNumber) 16 | } 17 | } 18 | ) 19 | 20 | setMethod( 21 | f="getReference", 22 | signature = signature("character"), 23 | definition = function(entity) { 24 | list(targetId=entity) 25 | } 26 | ) 27 | 28 | -------------------------------------------------------------------------------- /man/annotationValues_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{annotationValues<--methods} 2 | \docType{methods} 3 | \alias{annotationValues<--methods} 4 | \alias{annotationValues<-,SynapseAnnotation,list-method} 5 | \alias{annotationValues<-,SynapseEntity,list-method} 6 | \title{ Methods for Function \code{annotationValues<-} } 7 | \description{ 8 | Methods for function \code{annotationValues<-} 9 | } 10 | \section{Methods}{ 11 | \describe{ 12 | 13 | \item{\code{signature(entity = "SynapseAnnotation", value = "list")}}{ 14 | set the annotations in list to the SynapseAnnotation entity 15 | } 16 | 17 | \item{\code{signature(entity = "SynapseEntity", value = "list")}}{ 18 | set the annotations in list to the SynapseAnnotation entity held by the SynapseEntity 19 | } 20 | }} 21 | \keyword{methods} 22 | -------------------------------------------------------------------------------- /inst/resources/test/Test.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Test", 3 | "description": "This is a test entity definition", 4 | "type": "interface", 5 | "implements": [ 6 | { 7 | "$ref": "org.sagebionetworks.repo.model.Entity" 8 | } 9 | ], 10 | "properties": { 11 | "string": { 12 | "type": "string", 13 | "description": "string property", 14 | "title": "Name" 15 | }, 16 | "integer": { 17 | "type": "integer", 18 | "description": "integer property", 19 | "title": "Name" 20 | }, 21 | "numeric": { 22 | "type": "numeric", 23 | "description": "numeric property", 24 | "title": "Name" 25 | }, 26 | "transient": { 27 | "type": "string", 28 | "description": "transient string", 29 | "transient": true 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /man/synUpdateEntityACL.Rd: -------------------------------------------------------------------------------- 1 | \name{Update Entity Access Control List} 2 | \alias{synUpdateEntityACL} 3 | \docType{methods} 4 | \title{ 5 | Update Entity Access Control List 6 | } 7 | 8 | \description{ 9 | Updates an ACL for an entity (e.g. File, Folder, Table). 10 | } 11 | \usage{synUpdateEntityACL(acl)} 12 | \arguments{ 13 | \item{acl}{ 14 | The updated AccessControlList. This allows principals (users or teams) to be added or removed, or 15 | to change the access permissions of principals already in the ACL. 16 | } 17 | } 18 | \value{ 19 | The updated ACL. 20 | } 21 | 22 | \seealso{ 23 | \code{\link{synCreateEntityACL}} 24 | \code{\link{synGetEntityACL}} 25 | \code{\link{synDeleteEntityACL}} 26 | \code{\link{AccessControlList}} 27 | \code{\link{ResourceAccessList}} 28 | \code{\link{ResourceAccess}} 29 | } 30 | -------------------------------------------------------------------------------- /R/synapseLinkExternalFile.R: -------------------------------------------------------------------------------- 1 | # 2 | # synapseLinkExternalFile 3 | # 4 | # Bruce Hoff 5 | # 6 | # links external URL via the Synapse File Services, returning a FileHandle 7 | # 8 | 9 | synapseLinkExternalFile<-function(externalURL, contentType, contentSize, contentMd5, storageLocationId) { 10 | fileName<-basename(externalURL) 11 | if (is.null(contentType)) { 12 | contentType<-getMimeTypeForFile(fileName) 13 | } 14 | uri<- "/externalFileHandle" 15 | body<-list(externalURL=externalURL, 16 | fileName=fileName, 17 | contentType=contentType, 18 | contentSize=contentSize, 19 | contentMd5=contentMd5, 20 | concreteType="org.sagebionetworks.repo.model.file.ExternalFileHandle", 21 | storageLocationId=storageLocationId) 22 | synapsePost(uri, body, endpoint=synapseFileServiceEndpoint()) 23 | } -------------------------------------------------------------------------------- /tools/docGen/typedListTemplate.Rd: -------------------------------------------------------------------------------- 1 | \name{TypedList} 2 | ##alias## 3 | \docType{methods} 4 | \title{ 5 | Functions for typed lists 6 | } 7 | \description{Methods for typed lists.} 8 | \usage{ 9 | append(x, values, after = length(x)) 10 | 11 | set(x, values) 12 | 13 | getList(x) 14 | } 15 | \arguments{ 16 | \item{x}{ 17 | A typed list. 18 | } 19 | \item{values}{ 20 | Values to go into the list. Must be of the list's type. 21 | } 22 | \item{after}{ 23 | Insertion position. 24 | } 25 | } 26 | \details{ 27 | append() works as it does for lists, but requires that the values being appended match the type of the typed list. 28 | 29 | set() replaces all the values with those passed in, first checking that the type of the values is correct. 30 | 31 | getList() returns the underlying list. 32 | } 33 | 34 | -------------------------------------------------------------------------------- /inst/unitTests/test_usedListEntry.R: -------------------------------------------------------------------------------- 1 | # Unit tests for UsedListEntiry 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | unitTestUsedListEntry<-function() { 8 | usedEntry<-synapseClient:::usedListEntry(list(entity="syn123456", wasExecuted=T)) 9 | checkTrue(usedEntry$wasExecuted) 10 | checkEquals("org.sagebionetworks.repo.model.provenance.UsedEntity", usedEntry$concreteType) 11 | checkEquals("syn123456", usedEntry$reference$targetId) 12 | 13 | usedEntry<-synapseClient:::usedListEntry(list(url="http://foo.bar", wasExecuted=F)) 14 | checkTrue(!usedEntry$wasExecuted) 15 | checkEquals("org.sagebionetworks.repo.model.provenance.UsedURL", usedEntry$concreteType) 16 | checkEquals("http://foo.bar", usedEntry$url) 17 | checkEquals("http://foo.bar", usedEntry$name) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /man/synGetEntityACL.Rd: -------------------------------------------------------------------------------- 1 | \name{Get Entity Access Control List} 2 | \alias{synGetEntityACL} 3 | \docType{methods} 4 | \title{ 5 | Get Entity Access Control List 6 | } 7 | 8 | \description{ 9 | Retrieves an Access Control List (ACL) for an entity (e.g. Project, File, Folder, Table). 10 | } 11 | \usage{synGetEntityACL(id)} 12 | \arguments{ 13 | \item{id}{ 14 | The ID of the entity whose ACL is to be retrieved. If the entity inherits its ACL from a parent, an error 15 | is thrown. 16 | } 17 | } 18 | \value{ 19 | The entity's ACL. If the entity inherits the permissions of a parent, an error is thrown. 20 | } 21 | 22 | \seealso{ 23 | \code{\link{synCreateEntityACL}} 24 | \code{\link{synUpdateEntityACL}} 25 | \code{\link{synDeleteEntityACL}} 26 | \code{\link{AccessControlList}} 27 | \code{\link{ResourceAccessList}} 28 | \code{\link{ResourceAccess}} 29 | } 30 | -------------------------------------------------------------------------------- /man/sendMessage.Rd: -------------------------------------------------------------------------------- 1 | \name{sendMessage} 2 | \alias{sendMessage} 3 | \title{ 4 | sendMessage 5 | } 6 | \description{ 7 | Send a message to one or more Synapse users 8 | } 9 | \usage{ 10 | sendMessage(idList, messageSubject, messageBody) 11 | } 12 | \arguments{ 13 | \item{idList}{ 14 | A list of one or more Synapse User or Team IDs. Though IDs are numeric, they should be passed as character arguments. 15 | } 16 | \item{messageSubject}{ 17 | The message subject. 18 | } 19 | \item{messageBody}{ 20 | The message body. 21 | } 22 | } 23 | \details{ 24 | Email delivery of the message is subject to the recipient's delivery settings in Synapse. 25 | To send a message to the members of a Team, the sender must also be a member of the Team. 26 | } 27 | 28 | 29 | \examples{ 30 | \dontrun{ 31 | sendMessage(list("1234567"), "message subject", "message body") 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /man/used_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{used<--methods} 2 | \alias{used<-} 3 | \title{ 4 | \code{used<-} 5 | } 6 | \description{ 7 | Function for setting the entities used to generate an Entity or Activity. 8 | } 9 | \usage{ 10 | used(entity)<-list(entity1, entity2, entity3) 11 | used(entity)<-c(entity1, entity2, entity3) 12 | used(activity)<-list(entity1, entity2, entity3) 13 | used(activity)<-c(entity1, entity2, entity3) 14 | activity$used<-list(entity1, entity2, entity3) 15 | activity$used<-c(entity1, entity2, entity3) 16 | } 17 | \details{ 18 | Sets the vector or list of entities/entity IDs/URLs used (but not *executed*) to generate the given Entity or Activity. 19 | No server interaction takes place. (That is done when \code{storeEntity} is called.) To set the executed Entities, see \code{executed}. 20 | } 21 | 22 | 23 | \author{ 24 | Bruce Hoff 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /R/synapseDelete.R: -------------------------------------------------------------------------------- 1 | ## Send a Delete request to the Repository Services 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseDelete <- 7 | function( 8 | uri, 9 | endpoint=synapseServiceEndpoint("REPO"), 10 | curlHandle=getCurlHandle(), 11 | anonymous=FALSE, 12 | opts = .getCache("curlOpts"), 13 | checkHttpStatus=TRUE, 14 | logErrorsToSynapse=TRUE 15 | ) 16 | { 17 | ## constants 18 | kMethod <- "DELETE" 19 | ## end constants 20 | 21 | .synapseGetDelete(uri = uri, 22 | requestMethod = kMethod, 23 | endpoint = endpoint, 24 | curlHandle = curlHandle, 25 | anonymous = anonymous, 26 | opts = opts, 27 | checkHttpStatus=checkHttpStatus, 28 | logErrorsToSynapse=logErrorsToSynapse 29 | ) 30 | 31 | } -------------------------------------------------------------------------------- /R/getVersionInfo.R: -------------------------------------------------------------------------------- 1 | # 2 | # getVersionInfo 3 | # retrieves the black list / latest version info for the R client, using a cache to avoid repeated web calls 4 | # 5 | # 6 | 7 | getVersionInfo<-function(logErrorsToSynapse=TRUE) { 8 | cacheTimestampName<-"versionsInfoTimestamp" 9 | cacheVersionInfoName<-"versionsInfo" 10 | cacheRefreshSeconds<-300 # 5 minutes 11 | now<-Sys.time() 12 | cacheTimestamp<-.getCache(cacheTimestampName) 13 | versionInfo<-.getCache(cacheVersionInfoName) 14 | if (is.null(versionInfo) || is.null(cacheTimestamp) || Sys.time()-now>cacheRefreshSeconds) { 15 | response<-getURLWithRetries(.getVersionsEndpoint(), opts=.getCache("curlOpts"), logErrorsToSynapse=logErrorsToSynapse) 16 | versionInfo <- synFromJson(response$body) 17 | .setCache(cacheTimestampName, now) 18 | .setCache(cacheVersionInfoName, versionInfo) 19 | } 20 | versionInfo 21 | } 22 | -------------------------------------------------------------------------------- /man/executed_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{executed<--methods} 2 | \alias{executed<-} 3 | \title{ 4 | \code{executed<-} 5 | } 6 | \description{ 7 | Function for setting the entities executed to generate an Entity or Activity. 8 | } 9 | \usage{ 10 | executed(entity)<-list(entity1, entity2, entity3) 11 | executed(entity)<-c(entity1, entity2, entity3) 12 | executed(activity)<-list(entity1, entity2, entity3) 13 | executed(activity)<-c(entity1, entity2, entity3) 14 | activity$executed<-list(entity1, entity2, entity3) 15 | activity$executed<-c(entity1, entity2, entity3) 16 | } 17 | \details{ 18 | Sets the vector or list of entities/entity IDs/URLs executed to generate the given Entity or Activity. 19 | No server interaction takes place. (That is done when \code{storeEntity} is called.) To set the non-executed Entities, see \code{used}. 20 | } 21 | 22 | 23 | \author{ 24 | Bruce Hoff 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /man/synDeleteRows.Rd: -------------------------------------------------------------------------------- 1 | \name{synDeleteRows} 2 | \alias{synDeleteRows} 3 | \title{ 4 | synDeleteRows 5 | } 6 | \description{ 7 | Delete rows from a Synapse Table 8 | } 9 | \usage{ 10 | synDeleteRows(table) 11 | } 12 | \arguments{ 13 | \item{table}{ 14 | A TableDataFrame, having a table schema and a data frame, whose row labels indicate which rows to delete from the Synapse table. 15 | } 16 | } 17 | \details{ 18 | Deletes selected rows in Synapse. The passed data frame must have row labels in the format -, i.e. two integers 19 | separated by a dash ('-'). This is the label format for the data frames returned by synStore and synTableQuery. 20 | } 21 | 22 | \seealso{ 23 | \code{\link{synStore}} 24 | \code{\link{synTableQuery}} 25 | } 26 | \examples{ 27 | \dontrun{ 28 | queryResult<-synTableQuery("select * from syn1234 where foo='bar'") 29 | synDeleteRows(queryResult) 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /inst/integrationTests/test_createEntity.R: -------------------------------------------------------------------------------- 1 | .setUp <- 2 | function() 3 | { 4 | synapseClient:::.setCache('oldWarn', options('warn')[[1]]) 5 | options(warn=2) 6 | 7 | ## create a project 8 | project <- createEntity(Project()) 9 | synapseClient:::.setCache("testProject", project) 10 | 11 | synapseClient:::.setCache("oldCacheDir", synapseCacheDir()) 12 | synapseCacheDir(tempfile(pattern="tempSynapseCache")) 13 | } 14 | 15 | .tearDown <- 16 | function() 17 | { 18 | 19 | {project<-synapseClient:::.getCache("testProject") 20 | synRestDELETE(sprintf("/entity/%s?skipTrashCan=true", propertyValue(project, "id")))} 21 | synapseClient:::.deleteCache("testProject") 22 | 23 | unlink(synapseCacheDir(), recursive=T) 24 | synapseCacheDir(synapseClient:::.getCache("oldCacheDir")) 25 | 26 | options(warn=synapseClient:::.getCache("oldWarn")) 27 | synapseClient:::.deleteCache("oldWarn") 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /inst/unitTests/test_mergeColumns.R: -------------------------------------------------------------------------------- 1 | ## test mergeColumns object 2 | ## 3 | ## Author: J. Christopher Bare 4 | ############################################################################### 5 | 6 | unitTestMergeColumns <- function() { 7 | 8 | df <- data.frame(a=c(1,2,3), b=c('foo','bar','bat'), stringsAsFactors=FALSE) 9 | df2 <- synapseClient:::.mergeColumns(df, c('a.new.column','another.new.column')) 10 | checkEquals(ncol(df2), 4) 11 | checkEquals(nrow(df2), 3) 12 | checkEquals(df2$a, c(1,2,3)) 13 | checkEquals(df2$b, c('foo','bar','bat')) 14 | checkTrue(all(is.na(df2$a.new.column))) 15 | checkTrue(all(is.na(df2$another.new.column))) 16 | 17 | # no new columns 18 | df2 <- synapseClient:::.mergeColumns(df, c('a','b')) 19 | checkEquals(df,df2) 20 | 21 | # empty data.frame 22 | dfe <- synapseClient:::.mergeColumns(data.frame(), c('a','b','c')) 23 | checkEquals(nrow(dfe), 0) 24 | } 25 | -------------------------------------------------------------------------------- /man/synSetAnnotations.Rd: -------------------------------------------------------------------------------- 1 | \name{synSetAnnotations} 2 | \alias{synSetAnnotations} 3 | \docType{methods} 4 | \title{ 5 | synSetAnnotations 6 | } 7 | \description{ 8 | Set all the annotations on an entity. 9 | } 10 | \usage{synSetAnnotations(entity)<-values} 11 | \arguments{ 12 | \item{entity}{ 13 | The entity on which to set the annotations. 14 | } 15 | \item{values}{ 16 | A named list in which the names are the annotation names and the values are the annotation values. 17 | } 18 | } 19 | \examples{ 20 | \dontrun{ 21 | f <- File(path="/path/to/my/file.csv", parentId="syn1234") 22 | synSetAnnotations(f) <- list(tissueType="colon", platform="rnaseq") 23 | } 24 | } 25 | \seealso{ 26 | \code{\link{synGetAnnotations}} 27 | \code{\link{synGetProperties}} 28 | \code{\link{synSetProperties}} 29 | \code{\link{synGetAnnotation}} 30 | \code{\link{synSetAnnotation}} 31 | \code{\link{synGetProperty}} 32 | \code{\link{synSetProperty}} 33 | } 34 | -------------------------------------------------------------------------------- /R/synapseGet.R: -------------------------------------------------------------------------------- 1 | ## Send a get request to synapse 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseGet <- 7 | function(uri, 8 | endpoint=synapseServiceEndpoint("REPO"), 9 | curlHandle=getCurlHandle(), 10 | anonymous = .getCache("anonymous"), 11 | opts = .getCache("curlOpts"), 12 | checkHttpStatus=TRUE, 13 | logErrorsToSynapse=TRUE, 14 | extraRetryStatusCodes=NULL 15 | ) 16 | { 17 | ## constants 18 | kMethod <- "GET" 19 | ## end constants 20 | 21 | .synapseGetDelete(uri = uri, 22 | endpoint = endpoint, 23 | requestMethod = kMethod, 24 | curlHandle = curlHandle, 25 | anonymous = anonymous, 26 | opts = opts, 27 | checkHttpStatus=checkHttpStatus, 28 | logErrorsToSynapse=logErrorsToSynapse, 29 | extraRetryStatusCodes=extraRetryStatusCodes 30 | ) 31 | } 32 | 33 | -------------------------------------------------------------------------------- /configure: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Everything that needs to be done before building the package goes here: 3 | 4 | # download jar file from artifactory 5 | # note, this gets version 174.0. To change versions requires changing the following line in two places 6 | export srcjar=http://sagebionetworks.artifactoryonline.com/sagebionetworks/libs-releases-local/org/sagebionetworks/lib-auto-generated/174.0/lib-auto-generated-174.0.jar 7 | wget -O temp.jar $srcjar 8 | if [ "$?" -ne "0" ]; then 9 | curl -o temp.jar $srcjar 10 | fi 11 | if [ "$?" -ne "0" ]; then 12 | echo "Failed to download $srcjar" 13 | exit 1 14 | fi 15 | 16 | # extract schema into inst/resources 17 | unzip -oq temp.jar -d inst/resources 18 | # clean up downloaded jar file 19 | rm temp.jar 20 | 21 | # build the .Rd files 22 | # Note: We want to just call 'tools/docGen/createRdFiles.R .' but it doesn't work on cygwin (Windows) 23 | Rscript tools/docGen/createRdFiles.R . 24 | 25 | 26 | -------------------------------------------------------------------------------- /R/synapsePost.R: -------------------------------------------------------------------------------- 1 | ## Send a post request to Synapse 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapsePost <- 7 | function(uri, 8 | entity, 9 | endpoint=synapseServiceEndpoint("REPO"), 10 | curlHandle=getCurlHandle(), 11 | anonymous = FALSE, 12 | opts = .getCache("curlOpts"), 13 | checkHttpStatus=TRUE, 14 | logErrorsToSynapse=TRUE, 15 | extraRetryStatusCodes=NULL 16 | ) 17 | { 18 | ## constants 19 | kMethod <- "POST" 20 | ## end constants 21 | 22 | .synapsePostPut(uri = uri, 23 | entity = entity, 24 | endpoint = endpoint, 25 | requestMethod = kMethod, 26 | curlHandle = curlHandle, 27 | anonymous = anonymous, 28 | opts = opts, 29 | checkHttpStatus=checkHttpStatus, 30 | logErrorsToSynapse=logErrorsToSynapse, 31 | extraRetryStatusCodes=extraRetryStatusCodes 32 | ) 33 | } -------------------------------------------------------------------------------- /man/synGetSubmissionStatus.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetSubmissionStatus} 2 | \alias{synGetSubmissionStatus} 3 | \title{ 4 | synGetSubmissionStatus 5 | } 6 | \description{ 7 | Get the status of a Submission, given the submission ID. 8 | } 9 | \usage{ 10 | synGetSubmissionStatus(submission) 11 | synGetSubmissionStatus(submissionId) 12 | } 13 | \examples{ 14 | \dontrun{ 15 | # one of "RECEIVED","OPEN","CLOSED","SCORED","INVALID","VALIDATED","EVALUATION_IN_PROGRESS","REJECTED",or "ACCEPTED" 16 | status<-"SCORED" 17 | # get the first 100 submissions in the given evaluation queue having the given status 18 | submissions<-synGetSubmissions(evaluationId, status, limit=100, offset=0) 19 | # get the ID of an arbitrary Submission 20 | submissionId<-submissions@results[[1]]["id"] 21 | submission<-synGetSubmissionStatus(submissionId) 22 | } 23 | } 24 | \seealso{ 25 | \code{\link{synGetSubmissions}} 26 | \code{\link{synGetOwnSubmissions}} 27 | \code{\link{synGetSubmission}} 28 | } 29 | -------------------------------------------------------------------------------- /R/synapsePut.R: -------------------------------------------------------------------------------- 1 | ## Send a put request to Synapse 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapsePut <- 7 | function( 8 | uri, 9 | entity, 10 | endpoint=synapseServiceEndpoint("REPO"), 11 | curlHandle=getCurlHandle(), 12 | anonymous = FALSE, 13 | opts = .getCache("curlOpts"), 14 | checkHttpStatus=TRUE, 15 | logErrorsToSynapse=TRUE, 16 | extraRetryStatusCodes=NULL 17 | ) 18 | { 19 | ## constants 20 | kMethod <- "PUT" 21 | ## end constants 22 | 23 | .synapsePostPut(uri = uri, 24 | entity = entity, 25 | endpoint = endpoint, 26 | requestMethod = kMethod, 27 | curlHandle = curlHandle, 28 | anonymous = anonymous, 29 | opts = opts, 30 | checkHttpStatus=checkHttpStatus, 31 | logErrorsToSynapse=logErrorsToSynapse, 32 | extraRetryStatusCodes=extraRetryStatusCodes 33 | ) 34 | } -------------------------------------------------------------------------------- /R/synapseEndpoints.R: -------------------------------------------------------------------------------- 1 | # 2 | # Author: brucehoff 3 | ############################################################################### 4 | 5 | 6 | synSetEndpoints<-function(repoEndpoint, authEndpoint, fileEndpoint, portalEndpoint) { 7 | if (missing(repoEndpoint) && 8 | missing(authEndpoint) && 9 | missing(fileEndpoint) && 10 | missing(portalEndpoint)) { 11 | synapseResetEndpoints() 12 | } 13 | if (!missing(repoEndpoint)) synapseRepoServiceEndpoint(repoEndpoint) 14 | if (!missing(authEndpoint)) synapseAuthServiceEndpoint(authEndpoint) 15 | if (!missing(fileEndpoint)) synapseFileServiceEndpoint(fileEndpoint) 16 | if (!missing(portalEndpoint)) synapsePortalEndpoint(portalEndpoint) 17 | } 18 | 19 | synGetEndpoints<-function() { 20 | list(repo=synapseRepoServiceEndpoint()$endpoint, 21 | auth=synapseAuthServiceEndpoint()$endpoint, 22 | file=synapseFileServiceEndpoint()$endpoint, 23 | portal=synapsePortalEndpoint()$endpoint) 24 | } 25 | -------------------------------------------------------------------------------- /man/SynapseEntity.Rd: -------------------------------------------------------------------------------- 1 | \name{SynapseEntity} 2 | \alias{Study} 3 | \alias{Code} 4 | \alias{Data} 5 | \alias{Preview} 6 | \alias{ExpressionData} 7 | \alias{GenotypeData} 8 | \alias{PhenotypeData} 9 | \alias{RObject} 10 | \title{ 11 | DEPRECATED Entity Constructors 12 | } 13 | \description{ 14 | Constructors for Synapse Entities. These Constructors are now deprecated. Please see \code{\link{Project}}, \code{\link{Folder}}, \code{\link{File}} for currently supported Synapse Objects. 15 | } 16 | \usage{ 17 | Study(entity) 18 | Data(entity) 19 | Preview(entity) 20 | Link(entity) 21 | ExpressionData(entity) 22 | GenotypeData(entity) 23 | PhenotypeData(entity) 24 | RObject(entity) 25 | } 26 | \arguments{ 27 | \item{entity}{ 28 | (optional) a named list whose elements will be set as the properties of the entity. The list of 29 | valid properties is controlled by Synapse and currently no client-side verification is perfomed. 30 | } 31 | } 32 | 33 | \value{ 34 | The entity 35 | } 36 | \author{ 37 | Matthew D. Furia 38 | } 39 | -------------------------------------------------------------------------------- /R/onWeb.R: -------------------------------------------------------------------------------- 1 | ## Open the webpage of an entity 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################## 5 | 6 | 7 | setMethod( 8 | f = "onWeb", 9 | signature = "numeric", 10 | definition = function(entity){ 11 | onWeb(as.character(entity)) 12 | } 13 | ) 14 | 15 | setMethod( 16 | f = "onWeb", 17 | signature = "character", 18 | definition = function(entity){ 19 | utils::browseURL(.buildSynapseUrl(entity)) 20 | } 21 | ) 22 | 23 | .doOnWeb <- function(entity) { 24 | if(entity@synapseWebUrl == "") 25 | stop("This Entity has not been saved to Synapse yet. Use createEntity() to save it and then try again.") 26 | tryCatch( 27 | utils::browseURL(entity@synapseWebUrl), 28 | error = function(e){ 29 | warning("Unable to launch the web browser. Paste this url into your web browser: %s", entity@synapseWebUrl) 30 | warning(e) 31 | } 32 | ) 33 | invisible(entity@synapseWebUrl) 34 | } 35 | -------------------------------------------------------------------------------- /R/userProfile.R: -------------------------------------------------------------------------------- 1 | # synGetUserProfile 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | synGetUserProfile<-function(id) { 8 | if (missing(id)) { 9 | getOrUpdateUri<-"/userProfile" 10 | } else { 11 | getOrUpdateUri<-sprintf("/userProfile/%s", id) 12 | } 13 | response<-synRestGET(getOrUpdateUri) 14 | objectResult<-createS4ObjectFromList(response, "UserProfile") 15 | objectResult 16 | } 17 | 18 | userProfileUpdateAndDeleteUri<-function(obj) { 19 | sprintf("/userProfile",obj$ownerId) 20 | } 21 | 22 | setMethod( 23 | f = "synStore", 24 | signature = "UserProfile", 25 | definition = function(entity) { 26 | # note, user can't create a UserProfile, only update one 27 | updateS4Object(entity, userProfileUpdateAndDeleteUri(entity)) 28 | } 29 | ) 30 | 31 | synUpdateUserProfile<-function(userProfile) { 32 | updateS4Object(userProfile, userProfileUpdateAndDeleteUri(userProfile)) 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /inst/unitTests/test_AAAShared.R: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | 8 | unitTestGetEffectivePropertySchemas<-function() { 9 | # this schema implements *two* interfaces 10 | schemaName<-"org.sagebionetworks.repo.model.file.S3FileHandle" 11 | eps<-synapseClient:::getEffectivePropertySchemas(schemaName, synapseClient:::getSchemaPath()) 12 | checkTrue(any(names(eps)=="previewId")) 13 | checkTrue(any(names(eps)=="id")) 14 | } 15 | 16 | unitTest_ProblemString <- function(){ 17 | require(rjson) 18 | problemString <- "{\"foo\":\"b\\ar\"}" 19 | expected <- "b\ar" 20 | checkEquals(synapseClient:::synFromJson(problemString)$foo, expected) 21 | checkException(fromJSON(problemString)) 22 | } 23 | 24 | unitTest_synFromJson<-function() { 25 | checkEquals(list(foo="bar"), synapseClient:::synFromJson("{\"foo\":\"bar\"}")) 26 | checkEquals(list(foo="/bar"), synapseClient:::synFromJson("{\"foo\":\"\\/bar\"}")) 27 | } 28 | -------------------------------------------------------------------------------- /inst/integrationTests/test_tableColumn.R: -------------------------------------------------------------------------------- 1 | # 2 | # Author: brucehoff 3 | ############################################################################### 4 | 5 | 6 | integrationTestCreateColumn<-function() { 7 | name<-"R_Client_Integration_Test_Create_Column" 8 | # note, for the test to work they must be in alphabetical order, 9 | # since the values returned by the server are in this order 10 | enumValues<-c("bar", "bas", "foo") 11 | 12 | tableColumn<-TableColumn( 13 | name=name, 14 | columnType="STRING", 15 | defaultValue="foo", 16 | maximumSize=30, 17 | enumValues=enumValues) 18 | 19 | storedColumn<-synStore(tableColumn) 20 | 21 | # should be the same except for the ID 22 | checkTrue(!is.null(storedColumn$id)) 23 | id<-storedColumn$id 24 | storedColumn$id<-character(0) 25 | checkTrue(identical(storedColumn, tableColumn)) 26 | 27 | retrievedColumn<-synapseClient:::synGetColumn(id) 28 | storedColumn$id<-id 29 | checkTrue(identical(retrievedColumn, storedColumn)) 30 | } 31 | -------------------------------------------------------------------------------- /inst/unitTests/test_tableSchema.R: -------------------------------------------------------------------------------- 1 | # unit tests for TableSchema 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | unitTest_tableSchema<-function() { 8 | tableColumns<-list() 9 | for (i in 1:3) { 10 | tableColumn<-TableColumn(id=sprintf("%s", i), 11 | name=sprintf("R_Client_Unit_Test_Column_Name_%d", i), 12 | columnType="STRING") 13 | tableColumns<-append(tableColumns, tableColumn) 14 | } 15 | 16 | 17 | name<-sprintf("R_Client_Integration_Test_Create_Schema_%s", sample(999999999, 1)) 18 | 19 | tableSchema<-TableSchema(name, "syn123", tableColumns, foo="bar", "pi"=3.14) 20 | for (i in 1:3) { 21 | checkEquals(tableColumns[[i]], tableSchema@columns[[i]]) 22 | } 23 | 24 | checkEquals(FALSE, tableSchema@generatedByChanged) 25 | 26 | } 27 | 28 | unitTest_createTableSchemaFromProperties<-function() { 29 | id<-"syn101" 30 | ts<-synapseClient:::createTableSchemaFromProperties(list(id=id)) 31 | checkEquals(id, ts$properties$id) 32 | } 33 | -------------------------------------------------------------------------------- /man/synapseAuthServiceEndpoint.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseAuthServiceEndpoint} 2 | \alias{synapseAuthServiceEndpoint} 3 | \alias{synapseRepoServiceEndpoint} 4 | \alias{synapseFileServiceEndpoint} 5 | \alias{synapsePortalEndpoint} 6 | \alias{synapseResetEndpoints} 7 | \title{ 8 | Synapse Endpoints 9 | } 10 | \description{ 11 | Manage the Synapse endpoints 12 | } 13 | \usage{ 14 | synapseAuthServiceEndpoint(endpoint) 15 | synapseRepoServiceEndpoint(endpoint) 16 | synapseFileServiceEndpoint(endpoint) 17 | synapsePortalEndpoint(endpoint) 18 | synapseResetEndpoints() 19 | } 20 | \arguments{ 21 | \item{endpoint}{ 22 | The desired service endpoint 23 | } 24 | } 25 | \details{ 26 | If called with no arguments, get the desired endpoint. Otherwise, set the endpoint to the value provided. 27 | 28 | synapseResetEndpoints sets the four endpoints to their default values. 29 | } 30 | \value{ 31 | If called with no arguments, all but synapseResetEndpoints return the value of the endpoint. 32 | } 33 | \author{ 34 | Matt Furia 35 | } 36 | 37 | \seealso{ 38 | \code{\link{synapseLogin}} 39 | } 40 | -------------------------------------------------------------------------------- /man/synGetUserProfile.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetUserProfile} 2 | \alias{synGetUserProfile} 3 | \title{ 4 | synGetUserProfile 5 | } 6 | \description{ 7 | Function which retrieves a user profile. 8 | } 9 | \usage{ 10 | synGetUserProfile 11 | synGetUserProfile(principalId) 12 | } 13 | \details{ 14 | synGetUserProfile() returns the profile of the logged in user. synGetUserProfile(principalId) returns the profile of the 15 | specified user. User profiles have public and private fields. For example, first name and last name are public fields, 16 | while email address is private. When retrieving ones own user profile, all fields are returned. When retrieving 17 | another's profile, only the public fields are returned. 18 | } 19 | \examples{ 20 | \dontrun{ 21 | # get my own user profile 22 | profile<-synGetUserProfile() 23 | propertyValue(profile, "position")<-"Imperial Vice Duke of all Engineering" 24 | profile<-synStore(profile) 25 | # get someone else's profile 26 | principalId<-"123456" 27 | profile<-synGetUserProfile(principalId) 28 | } 29 | } 30 | \seealso{ 31 | \code{\link{UserProfile}} 32 | } -------------------------------------------------------------------------------- /man/synDownloadTableColumns.Rd: -------------------------------------------------------------------------------- 1 | \name{synDownloadTableColumns} 2 | \alias{synDownloadTableColumns} 3 | \docType{methods} 4 | \title{ 5 | synDownloadTableColumns 6 | } 7 | \description{ 8 | Download files referenced in a Table 9 | } 10 | \usage{ 11 | synDownloadTableColumns(synTable, tableColumns) 12 | } 13 | \arguments{ 14 | \item{synTable}{ 15 | The tabular data containing file references to download. Must be a TableDataFrame object returned from synTableQuery 16 | } 17 | \item{tableColumns}{ 18 | A character object listing the column(s) to be retrieved. 19 | } 20 | } 21 | \value{ 22 | Returns a list whose names are the fileHandle IDs found in the 23 | specified columns of the given Table and each value of which is 24 | the path to the requested file or NULL if the file was not able 25 | to be downloaded. 26 | } 27 | \details{ 28 | Downloads the files corresponding to the references in the selected rows of the 29 | given Table, while avoiding re-downloading those files which are already downloaded 30 | to the default download location. 31 | } 32 | \seealso{ 33 | \code{\link{synTableQuery}} 34 | } 35 | -------------------------------------------------------------------------------- /synapseRClient-assembly.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 8 | synapse-r-client-assembly 9 | 10 | zip 11 | 12 | false 13 | 14 | 15 | /synapseRClient 16 | ${project.basedir} 17 | 18 | DESCRIPTION 19 | NAMESPACE 20 | R/**/* 21 | man/**/* 22 | inst/**/* 23 | src/**/* 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /inst/unitTests/test_queryLimitAndOffset.R: -------------------------------------------------------------------------------- 1 | ## test queryLimitAndOffset 2 | ## 3 | ## Author: J. Christopher Bare 4 | ############################################################################### 5 | 6 | unitTestQueryLimitAndOffset <- function() { 7 | q <- "select id, name, parentId from code limit 456 offset 123" 8 | result <- synapseClient:::.queryLimitAndOffset(q) 9 | checkTrue(!is.null(result)) 10 | checkEquals(result$query, "select id, name, parentId from code") 11 | checkEquals(result$limit, 456) 12 | checkEquals(result$offset, 123) 13 | 14 | q <- "select * from dataset limit 100" 15 | result <- synapseClient:::.queryLimitAndOffset(q) 16 | checkTrue(!is.null(result)) 17 | checkEquals(result$query, "select * from dataset") 18 | checkEquals(result$limit, 100) 19 | checkEquals(result$offset, 1) 20 | 21 | q <- "select id, name, parentId from dataset offset 100" 22 | result <- synapseClient:::.queryLimitAndOffset(q) 23 | checkTrue(!is.null(result)) 24 | checkEquals(result$query, "select id, name, parentId from dataset") 25 | checkTrue(is.na(result$limit)) 26 | checkEquals(result$offset, 100) 27 | } 28 | -------------------------------------------------------------------------------- /inst/integrationTests/test_userProfile.R: -------------------------------------------------------------------------------- 1 | # Integration test for user profile 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | checkEqualsUserProfiles<-function(p1, p2) { 8 | slotNames<-c("ownerId", "uri", "etag", "firstName", "lastName") # etc. 9 | for (slotName in slotNames) { 10 | checkEquals(slot(p1, slotName), slot(p2, slotName)) 11 | } 12 | } 13 | 14 | integrationTestUserProfile<-function() { 15 | profile<-synGetUserProfile() 16 | origSummary<-propertyValue(profile, "summary") 17 | 18 | propertyValue(profile, "summary")<-"test summary text" 19 | profile2<-synStore(profile) 20 | propertyValue(profile, "etag")<-propertyValue(profile2, "etag") 21 | checkEqualsUserProfiles(profile2, profile) 22 | 23 | profile3<-synGetUserProfile() 24 | checkEqualsUserProfiles(profile3, profile) 25 | 26 | profile4<-synGetUserProfile(propertyValue(profile, "ownerId")) 27 | checkEqualsUserProfiles(profile4, profile) 28 | 29 | # restore to original settings 30 | propertyValue(profile, "summary")<-origSummary 31 | synStore(profile) 32 | } 33 | 34 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: synapseClient 2 | Type: Package 3 | Title: Synapse R Client from Sage Bionetworks 4 | Version: 1.15-3 5 | ReleaseNotes: Here are this version's release notes: https://sagebionetworks.jira.com/issues/?jql=project%20%3D%20SYNR%20AND%20fixVersion%20%3D%20R-1.15-0%20ORDER%20BY%20fixVersion%20ASC%2C%20key%20DESC 6 | Date: 2017-12-08 7 | Author@R: c( 8 | person("Bruce", "Hoff", email="bruce.hoff@sagebase.org", role="aut"), 9 | person("Chris", "Bare", email="chris.bare@sagebase.org", role="aut"), 10 | person("Martin", "Morgan", email="mtmorgan@fhcrc.org", role="ctb"), 11 | person("Brian", "Bot", email="brian.bot@sagebase.org", role="ctb") 12 | ) 13 | Author: Matthew Furia 14 | Maintainer: Bruce Hoff 15 | Depends: methods, R (>= 2.15) 16 | Imports: rjson, RCurl (> 1.95-3),tools,digest,utils 17 | Suggests: RUnit, rGithubClient, Rsftp 18 | Additional_repositories: https://github.com/Sage-Bionetworks/rGithubClient 19 | SystemRequirements: zip 20 | Description: Contains a set of functions for interacting with the Synapse REST services. 21 | URL: http://www.sagebase.org 22 | License: GPL 23 | LazyLoad: yes 24 | -------------------------------------------------------------------------------- /man/synTableQuery.Rd: -------------------------------------------------------------------------------- 1 | \name{synTableQuery} 2 | \alias{synTableQuery} 3 | \docType{methods} 4 | \title{ 5 | synTableQuery 6 | } 7 | \description{ 8 | Query a Synapse Table 9 | } 10 | \usage{synTableQuery(sqlString, loadResult=TRUE, verbose=TRUE, filePath=NULL)} 11 | \arguments{ 12 | \item{sqlString}{ 13 | The query to execute. For complete syntax description see: 14 | rest.synapse.org/POST/table/query/async/start.html. 15 | } 16 | \item{loadResult}{ 17 | If true then return the query result, else return the path of a csv file containing the result. 18 | } 19 | \item{verbose}{ 20 | If TRUE then print progress information while results are retrieved. 21 | } 22 | \item{filePath}{ 23 | File path to which the csv file version of the query is stored. If omitted the result will be written in the 24 | default file cache location. 25 | } 26 | } 27 | \value{ 28 | If loadResult is TRUE then the result is a Table object 29 | with a 'values' slot holding the query results as a data frame. 30 | If loadResult is FALSE then the result is a Table object with 31 | a 'filePath' slot holding the path to 32 | a csv-formatted file of results. 33 | } 34 | \seealso{ 35 | \code{\link{Table}} 36 | } 37 | -------------------------------------------------------------------------------- /man/propertyValue_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{propertyValue<--methods} 2 | \docType{methods} 3 | \alias{propertyValue<--methods} 4 | \alias{propertyValue<-,SynapseAnnotation,character-method} 5 | \alias{propertyValue<-,SynapseAnnotation,integer-method} 6 | \alias{propertyValue<-,SynapseAnnotation,logical-method} 7 | \alias{propertyValue<-,SynapseAnnotation,numeric-method} 8 | \alias{propertyValue<-,SynapseEntity,character-method} 9 | \title{ ~~ Methods for Function \code{propertyValue<-} ~~} 10 | \description{ 11 | ~~ Methods for function \code{propertyValue<-} ~~ 12 | } 13 | \section{Methods}{ 14 | \describe{ 15 | 16 | \item{\code{signature(object = "SynapseAnnotation", which = "character")}}{ 17 | set a character property 18 | } 19 | 20 | \item{\code{signature(object = "SynapseAnnotation", which = "integer")}}{ 21 | set an integer property 22 | } 23 | 24 | \item{\code{signature(object = "SynapseAnnotation", which = "logical")}}{ 25 | set a logical property 26 | } 27 | 28 | \item{\code{signature(object = "SynapseAnnotation", which = "numeric")}}{ 29 | set a numeric property 30 | } 31 | 32 | \item{\code{signature(object = "SynapseEntity", which = "character")}}{ 33 | set a character property 34 | } 35 | }} 36 | -------------------------------------------------------------------------------- /man/synGetOwnSubmissions.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetOwnSubmissions} 2 | \alias{synGetOwnSubmissions} 3 | \title{ 4 | synGetOwnSubmissions 5 | } 6 | \description{ 7 | Get the Submissions for a given Evaluation submitted by me. 8 | } 9 | \usage{ 10 | synGetOwnSubmissions(evaluationId, limit, offset) 11 | } 12 | \arguments{ 13 | \item{evaluationId}{ 14 | The evaluation queue containing the submissions of interest. 15 | } 16 | \item{limit}{ 17 | The optional limit 'paging' parameter, default is 10. 18 | } 19 | \item{offset}{ 20 | The optional offset 'paging' parameter, default is 0. 21 | } 22 | } 23 | \value{ 24 | an object of type PaginatedResults. Note, this function does not download files associated with Submissions. 25 | For that please see synGetSubmission. 26 | } 27 | \examples{ 28 | \dontrun{ 29 | # get the first 10 submissions in the given evaluation queue that I submitted. 30 | submissions<-synGetSubmissions(evaluationId, limit=10, offset=0) 31 | # get an arbitrary Submission from the list 32 | submission<-submissions@results[[1]] 33 | } 34 | } 35 | \seealso{ 36 | \code{\link{synGetSubmission}} 37 | \code{\link{synGetSubmissions}} 38 | \code{\link{synGetSubmissionStatus}} 39 | \code{\link{PaginatedResults}} 40 | } 41 | -------------------------------------------------------------------------------- /R/synapseRequest.R: -------------------------------------------------------------------------------- 1 | # synapseRequest 2 | # 3 | # calls getURL in RCurl after resolving permanent redirects 4 | # looks up synapse endpoint to construct URL from the given URI 5 | # 6 | # Author: brucehoff 7 | ############################################################### 8 | 9 | 10 | synapseRequest<-function( 11 | uri, # omitting the endpoint 12 | endpoint=synapseServiceEndpoint("REPO"), # one of REPO, AUTH, FILE 13 | postfields = NULL, # the request body 14 | customrequest, # the request method 15 | httpheader, # the headers 16 | curl, # the curl handle 17 | debugfunction = NULL, 18 | .opts, 19 | logErrorsToSynapse=TRUE, 20 | extraRetryStatusCodes=NULL) { 21 | 22 | endpoint<-resolvePermanentRedirects(endpoint, logErrorsToSynapse=logErrorsToSynapse) 23 | 24 | url <- paste(endpoint$endpoint, uri, sep="") 25 | 26 | result<-getURLWithRetries(url, 27 | postfields, # the request body 28 | customrequest, # the request method 29 | httpheader, # the headers 30 | curl, # the curl handle 31 | debugfunction, 32 | opts=.opts, 33 | logErrorsToSynapse, 34 | extraRetryStatusCodes=extraRetryStatusCodes) 35 | 36 | list(headers=result$parsedHeaders$headers, body=result$body) 37 | } 38 | 39 | -------------------------------------------------------------------------------- /man/Activity.Rd: -------------------------------------------------------------------------------- 1 | \name{Activity} 2 | \alias{Activity} 3 | \title{ 4 | Activity Constructor 5 | } 6 | \description{ 7 | Constructor for Activity 8 | } 9 | \usage{ 10 | Activity() 11 | } 12 | \arguments{ 13 | \item{properties}{ 14 | list(name="an activity", description="my description", used=list(e1, e2, ...), executed=list(e3, e4, ...)) 15 | where each of e1, e2, ... can be either a SynapseEntity, an entity ID ("syn1234"), or a URL. 16 | } 17 | } 18 | 19 | \value{ 20 | The created Activity is returned. 21 | } 22 | 23 | \section{Slots}{ 24 | \describe{ 25 | \item{\code{properties}}{ 26 | Synapse properties for an Activity object. 27 | Properties of interest include: 28 | \describe{ 29 | \item{\code{id}}{ 30 | unique Synapse ID as set by the system upon synStore (not set by user) 31 | } 32 | \item{\code{name}}{ 33 | user supplied name for the Activity 34 | } 35 | \item{\code{description}}{ 36 | user supplied description of the Activity 37 | } 38 | \item{\code{used}}{ 39 | Combination of 'used' and 'executed' arguments which makes up the upstream objects used by this Activity 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | \author{ 47 | Bruce Hoff 48 | } 49 | -------------------------------------------------------------------------------- /inst/unitTests/test_FileNameFromHeaders.R: -------------------------------------------------------------------------------- 1 | ## Unit test fileNameFromHeaders 2 | ## 3 | ## 4 | ############################################################################### 5 | 6 | 7 | 8 | unitTestMissingFileName <-function() { 9 | headers<-"Content-Type: text/html; charset=UTF-8\r\nDate: Sat, 28 Mar 2015 19:43:25 GMT\r\nExpires: Mon, 27 Apr 2015 19:43:25 GMT" 10 | checkTrue(is.null(synapseClient:::fileNameFromHeaders(headers))) 11 | } 12 | 13 | unitTestHappyCase <- function() { 14 | headers<-"x-amz-id-2: +iB0K6cFV3I1eUO7YIGJlF3Wn7GVxLKZEPsO1dbo5DYzwwo0lBVBlCqKV4W8S4w5\r\nx-amz-request-id: A2EA02790F1D642A\r\nDate: Thu, 26 Mar 2015 17:11:54 GMT\r\nContent-Disposition: attachment; filename=file7697fb85a1e.rbin\r\nLast-Modified: Tue, 13 Jan 2015 02:03:02 GMT\r\n" 15 | checkEquals(synapseClient:::fileNameFromHeaders(headers), "file7697fb85a1e.rbin") 16 | } 17 | 18 | unitTestWrongHeaderName <- function() { 19 | headers<-"x-amz-id-2: +iB0K6cFV3I1eUO7YIGJlF3Wn7GVxLKZEPsO1dbo5DYzwwo0lBVBlCqKV4W8S4w5\r\nx-amz-request-id: A2EA02790F1D642A\r\nDate: Thu, 26 Mar 2015 17:11:54 GMT\r\nNOT-Content-Disposition: attachment; filename=file7697fb85a1e.rbin\r\nLast-Modified: Tue, 13 Jan 2015 02:03:02 GMT\r\n" 20 | checkTrue(is.null(synapseClient:::fileNameFromHeaders(headers))) 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /inst/unitTests/test_memoryCache.R: -------------------------------------------------------------------------------- 1 | ## Unit tests for in-memory cache for global variables 2 | ## 3 | ## Author:Matthew D. Furia 4 | ############################################################################### 5 | 6 | .setUp <- 7 | function() 8 | { 9 | synapseClient:::.setCache("testGetKey", "testGetValue") 10 | synapseClient:::.setCache("testDeleteKey", "testDeleteValue") 11 | synapseClient:::.setCache("testSetKey", "testSetValue") 12 | } 13 | 14 | .tearDown <- 15 | function() 16 | { 17 | synapseClient:::.deleteCache("testGetKey") 18 | synapseClient:::.deleteCache("testDeleteKey") 19 | synapseClient:::.deleteCache("testSetKey") 20 | } 21 | 22 | unitTestGetCacheValue <- 23 | function() 24 | { 25 | checkEquals(synapseClient:::.getCache("testGetKey"), "testGetValue") 26 | } 27 | 28 | unitTestSetCacheValue <- 29 | function() 30 | { 31 | checkEquals(synapseClient:::.getCache("testSetKey"), "testSetValue") 32 | synapseClient:::.setCache("testSetKey", "testSetValueNew") 33 | checkEquals(synapseClient:::.getCache("testSetKey"), "testSetValueNew") 34 | } 35 | 36 | unitTestDeleteCacheValue <- 37 | function() 38 | { 39 | synapseClient:::.deleteCache("testDeleteKey") 40 | checkTrue(is.null(synapseClient:::.getCache("testDeleteKey"))) 41 | } -------------------------------------------------------------------------------- /man/synGetEvaluation.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetEvaluation} 2 | \alias{synGetEvaluation} 3 | \alias{synGetEvaluationByContentSource} 4 | \title{ 5 | synGetEvaluation 6 | } 7 | \description{ 8 | Function to retrieve an Evaluation object. 9 | } 10 | \usage{ 11 | synGetEvaluation(evaluationId) 12 | synGetEvaluationByContentSource(projectId) 13 | } 14 | \details{ 15 | synGetEvaluation retrieves an Evaluation object, given its ID. 16 | synGetEvaluationByContentSource retrieves all Evaluations that derive their content from a Project, give its ID. 17 | } 18 | \examples{ 19 | \dontrun{ 20 | # get an arbitrary Evaluation ID 21 | anEvaluationId<-synRestGET("/evaluation")$results[[1]]["id"] 22 | # retrieve the evaluation 23 | evaluation<-synGetEvaluation(anEvaluationId) 24 | # check its status 25 | propertyValue(evaluation, "status") 26 | # if I have administrative privileges I can update it 27 | propertyValue(evaluation, "description")<-"some new description" 28 | evaluation<-synStore(evaluation) 29 | 30 | # Or if you know a project with an evaluation 31 | # For example, the HPN-DREAM 1A challenge 32 | projectId <- "syn1720047" 33 | paginatedEvaluations <- synGetEvaluationByContentSource(projectId) 34 | evaluation <- paginatedEvaluations@results[[1]] 35 | } 36 | } 37 | \seealso{ 38 | \code{\link{synStore}} 39 | } 40 | -------------------------------------------------------------------------------- /man/setApiCredentials.Rd: -------------------------------------------------------------------------------- 1 | \name{setApiCredentials} 2 | \alias{setApiCredentials} 3 | \title{ 4 | setApiCredentials 5 | } 6 | \description{ 7 | Sets the user name and secret key used to sign authenticated web requests to Synapse. 8 | } 9 | \usage{ 10 | setApiCredentials(username, secretKey) 11 | } 12 | %- maybe also 'usage' for other objects documented here. 13 | \arguments{ 14 | \item{username}{ 15 | The user's name, i.e. email address 16 | } 17 | \item{secretKey}{ 18 | The secret key, retrieved from a previously authenticated session using hmacSecretKey(). 19 | } 20 | } 21 | \details{ 22 | Setting the user name and secret key provide an alternative to logging in with a password. 23 | This authentication method does not use an expiring token (rather each request has a time-limited 24 | digital signature based on the non-expiring secret key) and is therefore useful for long running jobs. 25 | } 26 | \author{ 27 | Bruce Hoff 28 | } 29 | 30 | \seealso{ 31 | \code{\link{synapseLogin}} 32 | \code{\link{hmacSecretKey}} 33 | } 34 | \examples{ 35 | \dontrun{ 36 | synapseLogin("user.name@sagebase.org", "foo", mode="hmac") 37 | key <- hmacSecretKey() 38 | synapseLogout() 39 | setApiCredentials("user.name@sagebase.org", key) 40 | # you may now make authenticated requests to Synapse 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /inst/unitTests/test_downloadFromServiceWithCaching.R: -------------------------------------------------------------------------------- 1 | # Unit test of downloadFromServiceWithCaching 2 | # 3 | # Author: bhoff 4 | ############################################################################### 5 | 6 | fileHandleId<-function() {"11111"} 7 | 8 | .setUp <- function() { 9 | unlink(synapseClient:::defaultDownloadLocation(fileHandleId()), recursive=T, force=T) 10 | 11 | content<-"this is a test" 12 | filePath<- tempfile(fileext = ".txt") 13 | connection<-file(filePath) 14 | writeChar(content, connection, eos=NULL) 15 | close(connection) 16 | 17 | synapseClient:::.setCache("filePath", filePath) 18 | 19 | synapseClient:::.mock("downloadFromService", function(...) {list(downloadedFile=filePath, fileName="foo.txt")}) 20 | 21 | } 22 | 23 | .tearDown <- function() { 24 | synapseClient:::.setCache("filePath", NULL) 25 | synapseClient:::.unmockAll() 26 | } 27 | 28 | unitTest_downloadFromServiceWithCaching<-function() { 29 | filePath<-synapseClient:::.getCache("filePath") 30 | synapseClient:::downloadFromServiceWithCaching("/foo", "FILE", fileHandleId(), tools::md5sum(path.expand(filePath))) 31 | } 32 | 33 | unitTest_downloadFromServiceWithCachingWrongMD5<-function() { 34 | checkException(synapseClient:::downloadFromServiceWithCaching("/foo", "FILE", fileHandleId(), "xxxxxxx")) 35 | } 36 | 37 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | This is an R client for the open-biology platform "Synapse". Visit https://www.synapse.org or http://www.sagebase.org for more info. To view documentation visit http://r-docs.synapse.org/. To file bug reports and feature requests visit http://sagebionetworks.jira.com/browse/SYNR. 2 | 3 | ## News 4 | A new R client '[synapser](https://github.com/Sage-Bionetworks/synapser)' is currently available at [Sage's RAN](https://sage-bionetworks.github.io/ran). 5 | 6 | ## Installation 7 | 8 | The R Synapse Client can be installed by typing these commands into the R prompt: 9 | 10 | ```R 11 | source("http://depot.sagebase.org/CRAN.R") 12 | pkgInstall(c("synapseClient")) 13 | ``` 14 | 15 | For early access to new and possibly not-ready-for-production features, you can install directly from GitHub using the `devtools` package. The _master_ branch will usually mirror the released version of the package. If you'd like to install the _develop_ branch, you can do so like this: 16 | 17 | ```R 18 | library(devtools) 19 | install_github('Sage-Bionetworks/rSynapseClient', ref='develop') 20 | ``` 21 | 22 | ## Getting Started 23 | 24 | The [Getting Started](http://docs.synapse.org/articles/getting_started.html) guide for Synapse includes examples for the R client. 25 | 26 | Full documentation for the R client is also available at http://docs.synapse.org/r/. 27 | 28 | 29 | -------------------------------------------------------------------------------- /R/synapseCacheDir.R: -------------------------------------------------------------------------------- 1 | ## get/set the Synapse cache directory locations 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseCacheDir <- function(cacheDir){ 7 | if(missing(cacheDir)){ 8 | return(.getCache("synapseCacheDir")) 9 | } 10 | 11 | if(is.null(cacheDir)) 12 | cacheDir <- "~/.synapseCache" 13 | 14 | if(!is.null(cacheDir) && cacheDir != "" && !file.exists(cacheDir)){ 15 | tryCatch({ 16 | dir.create(cacheDir, recursive=TRUE) 17 | }, 18 | error = function(e){ 19 | warning(sprintf("Unable to set cache directory to %s: e", cacheDir, e)) 20 | } 21 | ) 22 | } 23 | isdir <- file.info(cacheDir)$isdir 24 | if(is.na(isdir)){ 25 | ## don't warn 26 | } else if(file.access(cacheDir, 2) != 0L){ 27 | warning(sprintf("The requested cache directory '%s' is not writable so some features will\nnot be functional. Use the 'synapseCacheDir()' function to set a writable cache directory.", cacheDir)) 28 | } else if(!isdir){ 29 | warning(sprintf("Could not set cache directory to '%s' since a regular file with that name\n already exists. Some features will\nnot be functional. Use the 'synapseCacheDir()'\nfunction to set a writable cache directory.", cacheDir)) 30 | } 31 | .setCache("synapseCacheDir", cacheDir) 32 | } 33 | -------------------------------------------------------------------------------- /R/checkInteger.R: -------------------------------------------------------------------------------- 1 | ## return an boolean indicating whether the passed object is an integer. 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | checkInteger <- function(x){ 7 | result <- NULL 8 | if(length(x) == 0L) 9 | return(FALSE) 10 | for(i in 1:length(x)){ 11 | if(length(x) > 1){ 12 | xx <- x[[i]] 13 | }else{ 14 | xx <- x 15 | } 16 | if(any(isS4(xx)) | length(xx) == 0L | is.list(xx) | is.character(xx)){ 17 | result <- c(result, FALSE) 18 | }else{ 19 | suppressWarnings(thisVal <- tryCatch({ 20 | xx <- gsub("L$","",xx) # Remove trailing 'L' 21 | .Machine$double.eps > abs(as.integer(xx) - as.numeric(xx)) 22 | }, 23 | error = function(e) { rep(FALSE, length(xx)) } 24 | ) 25 | ) 26 | mk <- is.na(thisVal) | is.null(thisVal) 27 | if(any(mk)) { 28 | thisVal[mk] <- FALSE 29 | } 30 | if (class(try(as.character(xx), silent=TRUE)) != "try-error") { 31 | # as.integer() and as.numeric() may interpret a string as '0' 32 | xx <- gsub("^-","",xx) # Remove leading '-' 33 | if (regexpr('\\D', xx) >= 0) { 34 | thisVal <- FALSE 35 | } 36 | } 37 | result <- c(result, thisVal) 38 | } 39 | } 40 | result 41 | } 42 | -------------------------------------------------------------------------------- /R/getEntityInstance.R: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Author: furia 4 | ############################################################################### 5 | 6 | getFactoryForConcreteType<-function(concreteType) { 7 | factoryName<-NULL 8 | if (concreteType=="org.sagebionetworks.repo.model.FileEntity") factoryName<-"createFileFromProperties" 9 | if (concreteType=="org.sagebionetworks.repo.model.table.TableEntity") factoryName<-"createTableSchemaFromProperties" 10 | # by default the factory is a class constructor 11 | if (is.null(factoryName)) factoryName<-getClassNameFromSchemaName(concreteType) 12 | getMethod(factoryName, signature = "list", where="synapseClient") 13 | } 14 | 15 | setMethod( 16 | f = "getEntityInstance", 17 | signature = signature("list"), 18 | definition = function(entity) 19 | { 20 | if (is.null(entity$concreteType)) { 21 | stop("Entity metadata is missing 'concreteType'."); 22 | } else { 23 | factory <- getFactoryForConcreteType(entity$concreteType) 24 | } 25 | 26 | ## call the appropriate constructor and pass the list 27 | ## representation of the entity 28 | ee <- factory(entity) 29 | ee@synapseWebUrl <- .buildSynapseUrl(propertyValue(ee, "id")) 30 | ee 31 | } 32 | ) 33 | 34 | 35 | setMethod( 36 | f = "initializeEntity", 37 | signature = "Entity", 38 | definition = function(entity){ 39 | entity 40 | } 41 | ) 42 | 43 | 44 | -------------------------------------------------------------------------------- /inst/integrationTests/test_versions.R: -------------------------------------------------------------------------------- 1 | .setUp <- 2 | function() 3 | { 4 | project <- synStore(Project()) 5 | synapseClient:::.setCache("testProject", project) 6 | synapseClient:::.setCache("oldWarn", options("warn")[[1]]) 7 | } 8 | 9 | .tearDown <- 10 | function() 11 | { 12 | project<-synapseClient:::.getCache("testProject") 13 | synRestDELETE(sprintf("/entity/%s?skipTrashCan=true", propertyValue(project, "id"))) 14 | options(warn=synapseClient:::.getCache("oldWarn")) 15 | synapseClient:::.deleteCache("oldWarn") 16 | } 17 | 18 | 19 | integrationTestVersionedAnnotationsProject <- 20 | function() 21 | { 22 | options(warn=2) 23 | 24 | project <- synapseClient:::.getCache("testProject") 25 | vers <- project$available.versions 26 | checkEquals(1L, nrow(vers)) 27 | checkEquals("data.frame", class(vers)) 28 | 29 | ## versions the project 30 | project$annotations$aname <- "value1" 31 | project <- storeEntity(project) 32 | project$annotations$aname <- "value2" 33 | project <- storeEntity(project) 34 | vers <- project$available.versions 35 | checkEquals(1L, nrow(vers)) 36 | 37 | ## project versions do not change 38 | project <- getEntity(project$properties$id) 39 | checkEquals("value2", project$annotations$aname) 40 | project <- getEntity(project$properties$id, 1) 41 | checkEquals("value2", project$annotations$aname) 42 | 43 | } 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /inst/unitTests/test_getEntityInstance.R: -------------------------------------------------------------------------------- 1 | .setUp <- 2 | function() 3 | { 4 | synapseClient:::resetFactory(new("FileCacheFactory")) 5 | } 6 | 7 | .tearDown <- 8 | function() 9 | { 10 | synapseClient:::resetFactory(new("FileCacheFactory")) 11 | } 12 | 13 | xxxxTestGetDuplicateWithId <- 14 | function() 15 | { 16 | file <- tempfile() 17 | cat("THIS IS A TEST", file= file) 18 | root <- tempfile() 19 | url <- sprintf("http://fakedomain.com%s", root) 20 | 21 | entity <- list( 22 | id=basename(tempdir()), 23 | concreteType = "org.sagebionetworks.repo.model.Data", 24 | locations = list(list('path'= url)) 25 | ) 26 | 27 | ee <- synapseClient:::getEntityInstance(entity) 28 | ee2 <- synapseClient:::getEntityInstance(entity) 29 | 30 | addFile(ee, file) 31 | checkEquals(ee$files, ee2$files) 32 | checkEquals(ee$cacheDir, ee2$cacheDir) 33 | } 34 | 35 | xxxxTestGetDuplicateNoId <- 36 | function() 37 | { 38 | file <- tempfile() 39 | cat("THIS IS A TEST", file= file) 40 | root <- tempfile() 41 | url <- sprintf("http://fakedomain.com%s", root) 42 | 43 | entity <- list( 44 | concreteType = "org.sagebionetworks.repo.model.Data", 45 | locations = list(list('path'= url)) 46 | ) 47 | 48 | ee <- synapseClient:::getEntityInstance(entity) 49 | ee2 <- synapseClient:::getEntityInstance(entity) 50 | 51 | addFile(ee, file) 52 | checkEquals(ee$files, ee2$files) 53 | checkEquals(ee$cacheDir, ee2$cacheDir) 54 | } 55 | -------------------------------------------------------------------------------- /man/annotations.Rd: -------------------------------------------------------------------------------- 1 | \name{annotations} 2 | \alias{annotations} 3 | \alias{annotationValues} 4 | \alias{annotationValues<-} 5 | \alias{annotValue} 6 | \alias{annotValue<-} 7 | \alias{deleteAnnotation} 8 | \title{ 9 | Entity Annotations 10 | } 11 | \description{ 12 | Functions for manipulating object annotations 13 | } 14 | \usage{ 15 | annotations(object) 16 | annotationValues(object) 17 | annotValue(object, which) 18 | deleteAnnotation(object, which) 19 | } 20 | \arguments{ 21 | \item{object}{ 22 | The object whose annotations are being modified. 23 | } 24 | \item{which}{ 25 | An annotation name 26 | } 27 | } 28 | \value{ 29 | for deleteAnnotation and annotValue: 30 | The modified object. 31 | 32 | for annotations: 33 | an object of class SynapseAnnotations. 34 | 35 | for annotValue: 36 | the value stored for the annotation specified by "which" 37 | 38 | } 39 | 40 | \details{ 41 | annotValue is used to get or set a single annotation value. annotationValues is used to get all 42 | annotations as a list or to assign the elements of the list as annotations. 43 | 44 | the annotations() function should generally not be called by the end-user and may be deprecated 45 | in the future. 46 | } 47 | \note{ 48 | when using \code{annotationValues<-}, if the object already has an annotation with the same name 49 | as an element in the list, it's value will be overwritten. 50 | } 51 | 52 | \author{ 53 | Matt Furia 54 | } 55 | 56 | \seealso{ 57 | \code{\link{properties}} 58 | } 59 | -------------------------------------------------------------------------------- /R/synapseQuery.R: -------------------------------------------------------------------------------- 1 | ## Execute a Synapse Query 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseQuery <- 7 | function(queryStatement, blockSize=NULL) 8 | { 9 | ## Constants 10 | kPath <- "/query?query=" 11 | ## end constants 12 | 13 | if(!is.character(queryStatement)){ 14 | stop("a query statement must be supplied of R type character") 15 | } 16 | 17 | uri <- paste(kPath, curlEscape(queryStatement), sep="") 18 | 19 | if (is.null(blockSize)) { 20 | result <- synapseGet(uri=uri, anonymous=FALSE) 21 | 22 | if(result$totalNumberOfResults == 0){ 23 | return(NULL) 24 | } 25 | 26 | ## Parse response and prepare return value 27 | return.val <- .jsonListToDataFrame(result$results) 28 | attr(return.val, "totalNumberOfResults") <- result$totalNumberOfResults 29 | 30 | return(return.val) 31 | } 32 | else { 33 | 34 | if (!is.numeric(blockSize)) { 35 | stop("blockSize must be an integer") 36 | } 37 | 38 | return(QueryResult$new(queryStatement, blockSize=blockSize)) 39 | } 40 | 41 | } 42 | 43 | 44 | synQuery <- 45 | function(queryStatement, blockSize=NULL) 46 | { 47 | synapseQuery(queryStatement, blockSize) 48 | } 49 | 50 | 51 | md5Query <- function(md5) { 52 | kPath <- sprintf("/entity/md5/%s", md5) 53 | result <- synapseGet(uri=kPath) 54 | return(result[['results']]) 55 | } 56 | -------------------------------------------------------------------------------- /R/loadEntity.R: -------------------------------------------------------------------------------- 1 | ## Load Entity Objects 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | setMethod( 7 | f = "loadEntity", 8 | signature = signature("character", "missing"), 9 | definition = function(entity){ 10 | entity <- getEntity(entity) 11 | loadEntity(entity) 12 | } 13 | ) 14 | 15 | setMethod( 16 | f = "loadEntity", 17 | signature = signature("character", "character"), 18 | definition = function(entity, versionId){ 19 | entity <- getEntity(entity, versionId) 20 | loadEntity(entity, versionId) 21 | } 22 | ) 23 | 24 | setMethod( 25 | f = "loadEntity", 26 | signature = signature("character", "numeric"), 27 | definition = function(entity, versionId){ 28 | loadEntity(entity, as.character(versionId)) 29 | } 30 | ) 31 | 32 | setMethod( 33 | f = "loadEntity", 34 | signature = signature("numeric", "missing"), 35 | definition = function(entity){ 36 | loadEntity(as.character(entity)) 37 | } 38 | ) 39 | 40 | setMethod( 41 | f = "loadEntity", 42 | signature = signature("numeric", "character"), 43 | definition = function(entity, versionId){ 44 | loadEntity(as.character(entity), versionId) 45 | } 46 | ) 47 | setMethod( 48 | f = "loadEntity", 49 | signature = signature("numeric", "numeric"), 50 | definition = function(entity, versionId){ 51 | loadEntity(as.character(entity), as.character(versionId)) 52 | } 53 | ) 54 | 55 | 56 | -------------------------------------------------------------------------------- /R/SynRest.R: -------------------------------------------------------------------------------- 1 | # A collection of generic, public functions for making calls to the Synapse Rest API 2 | # 3 | # Note: As a convenience, if the 'body' of POST or PUT extends SimplePropertyOwner, 4 | # we convert it to a list before passing it on. 5 | # 6 | # Author: brucehoff 7 | ############################################################################### 8 | 9 | 10 | 11 | synRestGET<-function(uri, endpoint=synapseRepoServiceEndpoint()) { 12 | if (class(endpoint)=="list") endpointObject<-endpoint else endpointObject<-parseEndpoint(endpoint) 13 | synapseGet(uri, endpointObject) 14 | } 15 | 16 | synRestDELETE<-function(uri, endpoint=synapseRepoServiceEndpoint()) { 17 | if (class(endpoint)=="list") endpointObject<-endpoint else endpointObject<-parseEndpoint(endpoint) 18 | synapseDelete(uri, endpointObject) 19 | } 20 | 21 | synRestPOST<-function(uri, body, endpoint=synapseRepoServiceEndpoint()) { 22 | if (class(endpoint)=="list") endpointObject<-endpoint else endpointObject<-parseEndpoint(endpoint) 23 | if (is(body, "SimplePropertyOwner")) body<-as.list.SimplePropertyOwner(body) 24 | synapsePost(uri=uri, entity=body, endpoint=endpointObject) 25 | } 26 | 27 | synRestPUT<-function(uri, body, endpoint=synapseRepoServiceEndpoint()) { 28 | if (class(endpoint)=="list") endpointObject<-endpoint else endpointObject<-parseEndpoint(endpoint) 29 | if (is(body, "SimplePropertyOwner")) body<-as.list.SimplePropertyOwner(body) 30 | synapsePut(uri=uri, entity=body, endpoint=endpointObject) 31 | } 32 | 33 | -------------------------------------------------------------------------------- /man/synGetSubmissions.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetSubmissions} 2 | \alias{synGetSubmissions} 3 | \title{ 4 | synGetSubmissions 5 | } 6 | \description{ 7 | Get the Submissions for a given Evaluation. 8 | } 9 | \usage{ 10 | synGetSubmissions(evaluationId, status, limit, offset) 11 | } 12 | \arguments{ 13 | \item{evaluationId}{ 14 | The evaluation queue containing the submissions of interest. 15 | } 16 | \item{status}{ 17 | An optional filter on the submissions. One of "RECEIVED","OPEN","CLOSED","SCORED","INVALID","VALIDATED","EVALUATION_IN_PROGRESS","REJECTED",or "ACCEPTED". 18 | } 19 | \item{limit}{ 20 | The optional limit 'paging' parameter, default is 10. 21 | } 22 | \item{offset}{ 23 | The optional offset 'paging' parameter, default is 0. 24 | } 25 | } 26 | \value{ 27 | an object of type PaginatedResults. Note, this function does not download files associated with Submissions. 28 | For that please see synGetSubmission. 29 | } 30 | \examples{ 31 | \dontrun{ 32 | # one of "RECEIVED","OPEN","CLOSED","SCORED","INVALID","VALIDATED","EVALUATION_IN_PROGRESS","REJECTED",or "ACCEPTED" 33 | status<-"SCORED" 34 | # get the first 100 submissions in the given evaluation queue having the given status 35 | submissions<-synGetSubmissions(evaluationId, status, limit=100, offset=0) 36 | # get an arbitrary Submission from the list 37 | submission<-submissions@results[[1]] 38 | } 39 | } 40 | \seealso{ 41 | \code{\link{synGetSubmission}} 42 | \code{\link{synGetOwnSubmissions}} 43 | \code{\link{synGetSubmissionStatus}} 44 | \code{\link{PaginatedResults}} 45 | } 46 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 4.0.0 8 | 9 | 10 | client 11 | org.sagebionetworks 12 | 0.12-SNAPSHOT 13 | 14 | 15 | org.sagebionetworks 16 | synapseRClient 17 | pom 18 | Synapse R Client 19 | 20 | 21 | 22 | 24 | 25 | org.apache.maven.plugins 26 | maven-assembly-plugin 27 | 2.1 28 | 29 | 30 | synapseRClient-assembly.xml 31 | 32 | 33 | 34 | 35 | make-assembly 36 | package 37 | 38 | single 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /inst/unitTests/test_submit.R: -------------------------------------------------------------------------------- 1 | # Unit test for submitting to evaluation 2 | ############################################################################### 3 | 4 | .setUp <- 5 | function() { 6 | 7 | } 8 | 9 | .tearDown <- function() { 10 | synapseClient:::.unmockAll() 11 | } 12 | 13 | unitTestSubmit_no_submissionReceiptMessage <- function() { 14 | # Intercept all the calls to other methods 15 | synGetEvaluation_called <- FALSE 16 | createSubmissionFromProperties_called <- FALSE 17 | synCreateSubmission_called <- FALSE 18 | synapseClient:::.mock("synapseGet", function(uri, ...) { 19 | return(list(totalNumberOfResults=0)) 20 | }) 21 | synapseClient:::.mock("synGetEvaluation", function(id, ...) { 22 | synGetEvaluation_called <<- TRUE 23 | return(Evaluation(id=id)) 24 | }) 25 | synapseClient:::.mock("createSubmissionFromProperties", function(...) {createSubmissionFromProperties_called <<- TRUE}) 26 | synapseClient:::.mock("synCreateSubmission", function(...) {synCreateSubmission_called <<- TRUE}) 27 | 28 | # As per SYNR-626, pass in an ID, not an Evaluation object 29 | # The method should fetch the evaluation to show the proper confirmation message 30 | evaluation <- "evalId" 31 | entity <- File(id="fileId", parentId="parentId", etag="etag", name="name") 32 | submit(evaluation, entity) 33 | 34 | checkTrue(synGetEvaluation_called) 35 | checkTrue(createSubmissionFromProperties_called) 36 | checkTrue(synCreateSubmission_called) 37 | } 38 | 39 | -------------------------------------------------------------------------------- /R/checkCurlResponse.R: -------------------------------------------------------------------------------- 1 | ## Check the response of the curl request. throw an error if an http error 2 | ## code is returned. 3 | ## 4 | ## Author: Matthew D. Furia 5 | ############################################################################### 6 | 7 | .checkCurlResponse <- function(object, response, call.=FALSE, logErrorToSynapse=FALSE){ 8 | if(class(object) != "CURLHandle") stop("invalid curl handle") 9 | info <- .getCurlInfo(object) 10 | responseStatus<-info$response.code 11 | if (isErrorResponseStatus(responseStatus)) { 12 | url<-info$effective.url 13 | host<-"" 14 | if (!is.null(url) && nchar(url)>0) { 15 | parsedUrl<-.ParsedUrl(url) 16 | host<-parsedUrl@host 17 | } 18 | label<-paste(responseStatus, host) 19 | message <- paste("HTTP Error:", responseStatus, "for request", url) 20 | if (!missing(response)) { 21 | if (logErrorToSynapse) logErrorToSynapse(label, paste(message, response, sep = '\n')) 22 | stop(paste(message, response, sep = '\n'), call.=call.) 23 | } else { 24 | if (logErrorToSynapse) logErrorToSynapse(label, message=message) 25 | stop(message, call.=call.) 26 | } 27 | } 28 | } 29 | 30 | isErrorResponseStatus<-function(responseStatus) { 31 | responseStatus != 0 & (responseStatus < 200 || responseStatus >= 300) 32 | } 33 | 34 | # gets the status code for the given CurlHandle, 35 | getStatusCode<-function(object) { 36 | if(class(object) != "CURLHandle") stop("invalid curl handle") 37 | info <- .getCurlInfo(object) 38 | info$response.code 39 | } 40 | -------------------------------------------------------------------------------- /man/submit.Rd: -------------------------------------------------------------------------------- 1 | \name{submit} 2 | \alias{submit} 3 | \docType{methods} 4 | \title{ 5 | submit 6 | } 7 | \description{ 8 | Submit an entity to an Evaluation 9 | } 10 | \usage{submit(evaluation, entity, submissionName, teamName)} 11 | \arguments{ 12 | \item{evaluation}{ 13 | The evaluation queue to which the entity is submitted. You must first 'join' the evaluation to be allowed to submit. 14 | This parameter may be the ID of the evaluation or the evaluation object itself. 15 | } 16 | \item{entity}{ 17 | The entity to be submitted, e.g. a File. 18 | } 19 | \item{submissionName}{ 20 | Optional: A name for the submission. If omitted, the entity's name is used. 21 | } 22 | \item{teamName}{ 23 | Optional: The name of the team on whose behalf the entity is submitted. 24 | } 25 | \item{silent}{ 26 | Optional: Defaults to FALSE. If TRUE then do not print out the submission confirmation message. 27 | } 28 | } 29 | \details{ 30 | The content of the given entity is added to the given evaluation queue. Since the content is extracted, changing the entity 31 | after submission does not change what is in the queue. 32 | } 33 | \value{ 34 | A named list having two fields, 'createdSubmission' is the Submission object created by the server; 'submissionReceiptMessage' 35 | is the message acknowledging submission receipt (as customized by the Evaluation queue). 36 | } 37 | \seealso{ 38 | \code{\link{synGet}} 39 | \code{\link{synGetEvaluation}} 40 | \code{\link{synGetSubmission}} 41 | \code{\link{synGetSubmissions}} 42 | \code{\link{synGetOwnSubmissions}} 43 | \code{\link{synGetSubmissionStatus}} 44 | } 45 | -------------------------------------------------------------------------------- /R/queryLimitAndOffset.R: -------------------------------------------------------------------------------- 1 | ## Extract limit and offset from a synapse query 2 | ## 3 | ## Author: J. Christopher Bare 4 | ############################################################################### 5 | 6 | ## Extract limit and offset from a synapse query. 7 | ## Returns a list containing the modified query statement and, if specified, limit and offset. 8 | .queryLimitAndOffset <- 9 | function(queryStatement, default.limit=as.integer(NA), default.offset=1L) { 10 | 11 | result <- list(limit=default.limit, offset=default.offset) 12 | 13 | # check for limit in the query 14 | re.limit <- ".*limit\\s+(\\d+).*" 15 | if (grepl(re.limit, queryStatement, ignore.case=TRUE)) { 16 | 17 | # retrieve limit from query statement 18 | result$limit <- as.integer(sub(re.limit, "\\1", queryStatement, ignore.case=TRUE)) 19 | 20 | # remove limit from query 21 | queryStatement <- sub("\\s*limit\\s+\\d+\\s*"," ",queryStatement, ignore.case=TRUE) 22 | 23 | } 24 | 25 | # check for offset in the query 26 | re.offset <- ".*offset\\s+(\\d+).*" 27 | if (grepl(re.offset, queryStatement, ignore.case=TRUE)) { 28 | 29 | # take offset out of query 30 | result$offset <- as.integer(sub(re.offset, "\\1", queryStatement, ignore.case=TRUE)) 31 | 32 | # remove offset from query 33 | queryStatement <- sub("\\s*offset\\s+\\d+\\s*"," ",queryStatement, ignore.case=TRUE) 34 | 35 | } 36 | 37 | # clean up trailing whitespace in queries 38 | queryStatement <- sub("\\s+$", "", queryStatement) 39 | 40 | result$query <- queryStatement 41 | 42 | return(result) 43 | } -------------------------------------------------------------------------------- /R/xxxAccessControlList.R: -------------------------------------------------------------------------------- 1 | # accessors for Access Control Lists 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | synCreateEntityACL<-function(acl) { 7 | uri<-sprintf("/entity/%s/acl", acl@id) 8 | createS4ObjectFromList(synRestPOST(uri, createListFromS4Object(acl)), "AccessControlList") 9 | } 10 | 11 | synGetEntityACL<-function(entityId) { 12 | uri<-sprintf("/entity/%s/acl", entityId) 13 | createS4ObjectFromList(synRestGET(uri), "AccessControlList") 14 | } 15 | 16 | synUpdateEntityACL<-function(acl) { 17 | uri<-sprintf("/entity/%s/acl", acl@id) 18 | createS4ObjectFromList(synRestPUT(uri, createListFromS4Object(acl)), "AccessControlList") 19 | } 20 | 21 | synDeleteEntityACL<-function(entityId) { 22 | synRestDELETE(sprintf("/entity/%s/acl", entityId)) 23 | } 24 | 25 | showContent<-function(acl) { 26 | result<-sprintf("Access Control List for %s, created on %s\n", acl$id, acl$creationDate) 27 | if (isNullSlot(acl@resourceAccess)) { 28 | result<-paste(result, "\t**no ACL entries**\n", sep="") 29 | } else { 30 | for (ra in acl@resourceAccess@content) { 31 | result<-paste(result, 32 | sprintf("\tPrincipal ID %s has access type(s): %s\n", 33 | ra@principalId, paste(ra@accessType, collapse=", ")) 34 | , sep="") 35 | } 36 | } 37 | result 38 | } 39 | 40 | setMethod( 41 | f = "show", 42 | signature = signature("AccessControlList"), 43 | definition = function(object) { 44 | cat(showContent(object)) 45 | } 46 | ) 47 | 48 | 49 | # TODO write functions for managing Evaluation ACLs 50 | 51 | -------------------------------------------------------------------------------- /man/WikiPage.Rd: -------------------------------------------------------------------------------- 1 | \name{WikiPage} 2 | \alias{WikiPage} 3 | \docType{methods} 4 | \title{ 5 | Constructor for WikiPage 6 | } 7 | \description{ 8 | Constructor for WikiPage 9 | } 10 | \usage{ 11 | WikiPage(owner, title="Wiki Page for Entity", markdown="markdown goes here", attachments=list(file1, file2, ...) ) 12 | WikiPage(owner, title="Sub-Wiki Page for Entity", markdown="sub-page markdown goes here", parentWikiId="123456") 13 | } 14 | \details{ 15 | This creates a wiki page (in memory), or sub-page beneath an existing page for the given entity. 16 | } 17 | 18 | \section{Slots}{ 19 | \describe{ 20 | \item{\code{createUri}}{uri to create this WikiPage} 21 | \item{\code{updateUri}}{uri to update this WikiPage} 22 | \item{\code{attachments}}{attachments to be uploaded with the WikiPage} 23 | \item{\code{properties}}{ 24 | Synapse properties for a WikiPage. Properties of interest include: 25 | \describe{ 26 | \item{\code{id}}{unique Synapse ID as set by the system upon synStore (not set by user)} 27 | \item{\code{parentWikiId}}{the id of another WikiPage, if this WikiPage is a subpage of another WikiPage} 28 | \item{\code{title}}{user supplied title for the WikiPage} 29 | \item{\code{markdown}}{character string containing the markdown to be rendered on the WikiPage} 30 | } 31 | } 32 | } 33 | } 34 | 35 | 36 | \examples{ 37 | \dontrun{ 38 | entity<-synGet("syn123456") 39 | page<-WikiPage(owner=entity, title="Wiki Page for Entity", markdown="markdown goes here") 40 | page<-synStore(page) 41 | } 42 | } 43 | \seealso{ 44 | \code{\link{synGetWiki}} 45 | \code{\link{synStore}} 46 | } 47 | -------------------------------------------------------------------------------- /inst/unitTests/test_getCachedInLocation.R: -------------------------------------------------------------------------------- 1 | ## Unit test getCachedInLocation 2 | ## 3 | ## 4 | ############################################################################### 5 | 6 | createFile<-function(content, filePath) { 7 | if (missing(content)) content<-"this is a test" 8 | if (missing(filePath)) filePath<- tempfile() 9 | connection<-file(filePath) 10 | writeChar(content, connection, eos=NULL) 11 | close(connection) 12 | filePath 13 | } 14 | 15 | .tearDown <- function() { 16 | unlink(synapseClient:::cacheMapFilePath(10100)) 17 | } 18 | 19 | unitTestGetCachedInLocation <-function() { 20 | fileHandleId<-10100 21 | filePath1<-createFile() 22 | filePath2<-createFile() 23 | 24 | # filePath1 will be in the cacheMap, but with a last-modified date of yesterday 25 | day_incr <- -1 26 | mod_timestamp<-as.Date(as.numeric( 27 | synapseClient:::lastModifiedTimestamp(filePath1))/(24*3600)+day_incr, 28 | "1970-01-01") 29 | synapseClient:::addToCacheMap(fileHandleId, filePath1, timestamp=mod_timestamp) 30 | 31 | # filePath2 is in the cacheMap, unmodified 32 | synapseClient:::addToCacheMap(fileHandleId, filePath2) 33 | 34 | result<-synapseClient:::getCachedInLocation(fileHandleId, dirname(filePath1)) 35 | checkEquals(normalizePath(result$any), normalizePath(filePath1)) 36 | checkEquals(normalizePath(result$unchanged), normalizePath(filePath2)) 37 | 38 | # findCachedFile is like getCachedInLocation but is not specific to any location 39 | result<-synapseClient:::findCachedFile(fileHandleId) 40 | checkEquals(normalizePath(result$any), normalizePath(filePath1)) 41 | checkEquals(normalizePath(result$unchanged), normalizePath(filePath2)) 42 | 43 | } 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /R/Config.R: -------------------------------------------------------------------------------- 1 | 2 | ConfigParser <- function(path) { 3 | config <- new("Config") 4 | configFile <- .checkAndReadFile(path) 5 | section = NULL 6 | for (line in configFile) { 7 | # Sections 8 | matches <- regexec("\\[(.+)\\]", line) 9 | matches <- unlist(regmatches(line, matches)) 10 | if (length(matches) > 1) { 11 | section <- matches[2] 12 | # Keep all items if there are repeated sections 13 | if (!(section %in% names(config@data))) { 14 | config@data[[section]] <- list() 15 | } 16 | next 17 | } 18 | 19 | # Options and values 20 | matches <- regexec("\\s*([^:=]+)\\s*[:=]\\s*(\\S.*)\\s*", line) 21 | matches <- unlist(regmatches(line, matches)) 22 | if (length(matches) > 2) { 23 | matches <- sapply(matches, function(vec){ gsub("(^ +)|( +$)", "", vec) }) 24 | config@data[[section]][[matches[[2]]]] <- matches[[3]] 25 | } 26 | } 27 | 28 | return(config) 29 | } 30 | 31 | .checkAndReadFile <- function(path) { 32 | if (missing(path)) { 33 | path <- "~/.synapseConfig" 34 | } 35 | if (!file.exists(path)) { 36 | stop(sprintf("Configuration file '%s' cannot be found.", path)) 37 | } 38 | return(readLines(path)) 39 | } 40 | 41 | Config.hasSection <- function(config, section) { 42 | return(section %in% names(config@data)) 43 | } 44 | 45 | Config.hasOption <- function(config, section, option) { 46 | return(option %in% names(config@data[[section]])) 47 | } 48 | 49 | Config.getOption <- function(config, section, option) { 50 | return(config@data[[section]][[option]]) 51 | } 52 | -------------------------------------------------------------------------------- /man/Project.Rd: -------------------------------------------------------------------------------- 1 | \name{Project} 2 | \alias{Project} 3 | \title{ 4 | Synapse Project Constructor 5 | } 6 | \description{ 7 | Constructor for Project 8 | } 9 | \usage{ 10 | Project(name, ...) 11 | } 12 | \arguments{ 13 | \item{name}{ 14 | Name of the Project to be created in Synapse 15 | } 16 | \item{...}{ 17 | Additional named parameters are interpreted as properties or annotations on the Project 18 | } 19 | } 20 | 21 | \value{ 22 | The created Project is returned. NOTE: This is an in-memory representation. To persist to Synapse use \code{\link{synStore}()}. 23 | } 24 | 25 | \section{Slots}{ 26 | \describe{ 27 | \item{\code{attachOwn}}{ 28 | internally used information to handle file caching 29 | } 30 | \item{\code{annotations}}{ 31 | annotations set on the object 32 | } 33 | \item{\code{synapseEntityKind}}{ 34 | in this case, 'Project' 35 | } 36 | \item{\code{synapseWebUrl}}{ 37 | Synapse web URL 38 | } 39 | \item{\code{generatedBy}}{ 40 | the Activity which generated this Project, if applicable (see \code{\link{Activity}}) 41 | } 42 | \item{\code{properties}}{ 43 | Synapse properties for a Project. Properties of interest include: 44 | \describe{ 45 | \item{\code{id}}{ 46 | unique Synapse ID as set by the system upon synStore (not set by user) 47 | } 48 | \item{\code{name}}{ 49 | user supplied name 50 | } 51 | \item{\code{description}}{ 52 | user supplied description 53 | } 54 | } 55 | } 56 | } 57 | } 58 | 59 | 60 | \author{ 61 | Bruce Hoff 62 | } 63 | 64 | \seealso{ 65 | \code{\link{File}} 66 | \code{\link{Folder}} 67 | \code{\link{synGet}} 68 | \code{\link{synStore}} 69 | } 70 | -------------------------------------------------------------------------------- /R/resolvePermanentRedirect.R: -------------------------------------------------------------------------------- 1 | ## 2 | ## resolvePermanentRedirects 3 | ## 4 | ## resolve the permanent redirects for a service endpoint 5 | ## 6 | ## 7 | #################################################################### 8 | 9 | resolvePermanentRedirects<-function(endpoint, logErrorsToSynapse) { 10 | 11 | # we need to related permanent redirects to some service (e.g. REPO, AUTH, FILE) 12 | # if no service is specified then we use the 'host' portion of the endpoint as a proxy 13 | if (is.null(endpoint$service)) { 14 | endpoint$service<-endpoint$endpointHost 15 | } 16 | 17 | # need to make sure that permanent redirects have been resolved: 18 | redirectResolvedKey <- sprintf("permanent.redirects.resolved.%s", endpoint$service) 19 | redirectResolvedStatus <- .getCache(redirectResolvedKey) 20 | if (is.null(redirectResolvedStatus)) { 21 | # this will follow redirects and update the service endpoint globally 22 | redirectResult<-synapseGetFollowingPermanentRedirects( 23 | uri="/nonexistentservice", # non-existent service, just to trigger the redirect 24 | endpoint=endpoint, 25 | httpheader=.getCache("curlHeader"), 26 | curl=getCurlHandle(), 27 | debugfunction = NULL, 28 | .opts=.getCache("curlOpts"), 29 | logErrorsToSynapse=logErrorsToSynapse) 30 | # we expect a 404 error since we called a non-existent service 31 | # might also get a 401 error if authentication is required 32 | status<-redirectResult$parsedHeaders$statusCode 33 | if (status<400 || status>=500) stop(sprintf("Expected HTTP Status 4xx but found %s", status)) 34 | .setCache(redirectResolvedKey, TRUE) 35 | } 36 | 37 | # return the up-to-date endpoint 38 | synapseServiceEndpoint(endpoint$service) 39 | } -------------------------------------------------------------------------------- /inst/unitTests/test_table.R: -------------------------------------------------------------------------------- 1 | # unit tests for supporting functions in Table.R 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | unitTest_parseRowAndVersion<-function() { 7 | checkEquals(synapseClient:::parseRowAndVersion(c("1_2", "2_3", "3_2")), rbind(c(1,2,3), c(2,3,2))) 8 | checkEquals(synapseClient:::parseRowAndVersion(c("1_2", "2_3", "3")), rbind(c(1,2,NA), c(2,3,NA))) 9 | } 10 | 11 | unitTest_findSynIdInSql<-function() { 12 | checkEquals("syn123", synapseClient:::findSynIdInSql("select * from syn123")) 13 | checkEquals("syn123", synapseClient:::findSynIdInSql("select * from syn123 where foo=bar")) 14 | checkEquals("syn123", synapseClient:::findSynIdInSql("select * FrOm SyN123 where foo=bar")) 15 | checkEquals("syn123", synapseClient:::findSynIdInSql("select * from\tsyn123\twhere foo=bar")) 16 | } 17 | 18 | # checks values and column labels, but not row labels 19 | # we have to use this to compare data frames that have NAs 20 | dataFramesAreSame<-function(df1, df2) { 21 | if (nrow(df1)!=nrow(df2) || ncol(df1)!=ncol(df2)) return(FALSE) 22 | if (any(names(df1)!=names(df2))) return(FALSE) 23 | if (nrow(df1)==0 || ncol(df1)==0) return(TRUE) 24 | for (r in 1:nrow(df1)) { 25 | for (c in 1:ncol(df1)) { 26 | if (!identical(df1[r,c], df2[r,c])) return(FALSE) 27 | } 28 | } 29 | TRUE 30 | } 31 | 32 | unitTest_csvRoundTrip<-function() { 33 | dataFrame <- data.frame(sweet=c(1:5, 1.234e-10, 5.678e+10, NA), sweet2=c(NA, 6:10, 1.234567, 9.876543)) 34 | filePath<-tempfile() 35 | synapseClient:::writeDataFrameToCSV(dataFrame, filePath) 36 | readBackIn<-synapseClient:::readDataFrameFromCSV(filePath) 37 | checkTrue(dataFramesAreSame(dataFrame,readBackIn)) 38 | } -------------------------------------------------------------------------------- /man/sessionToken.Rd: -------------------------------------------------------------------------------- 1 | \name{sessionToken} 2 | \alias{refreshSessionToken} 3 | \alias{sessionToken} 4 | 5 | \title{ 6 | Refresh the Auth Service Session Token 7 | } 8 | \description{ 9 | Resets the counter in the Synapse auth service that determines when the token expires. 10 | } 11 | \usage{ 12 | sessionToken(sessionToken, checkValidity = FALSE, refreshDuration = .getCache("sessionRefreshDurationMin")) 13 | refreshSessionToken(sessionToken) 14 | } 15 | \arguments{ 16 | \item{sessionToken}{ 17 | Session token returned by the Synapse auth service 18 | } 19 | \item{checkValidity}{ 20 | boolean indicating whether the session token's validity should be checked before setting it 21 | in the memory cache and before returning it to the caller 22 | } 23 | \item{refreshDuration}{ 24 | duration that should be allowed to elapse before refreshing the session token 25 | } 26 | } 27 | 28 | \value{ 29 | refreshSessionToken has no return value, but is called for it's side-effects. The first side effect is that the expiration counter maintained by 30 | the Synapse auth service is reset. The second is that the local timestamp cache value is reset. 31 | 32 | sessionToken returns the current value of the session token. If the user is not logged in to 33 | Synapse, the function returns an empty string. 34 | } 35 | \author{ 36 | Matt Furia 37 | } 38 | \note{ 39 | This function will throw an exception if the session token is invalid or is already expired. Also, this method is for internal 40 | use only. 41 | } 42 | 43 | 44 | \seealso{ 45 | \code{\link{synapseLogin}} 46 | } 47 | \examples{ 48 | 49 | ## Not run: 50 | \dontrun{ 51 | synapseLogin('demouser@sagebase.org','demouser-pw') 52 | refreshSessionToken(sessionToken()) 53 | } 54 | ## End (Not run) 55 | } 56 | -------------------------------------------------------------------------------- /man/synGetSubmission.Rd: -------------------------------------------------------------------------------- 1 | \name{synGetSubmission} 2 | \alias{synGetSubmission} 3 | \title{ 4 | synGetSubmission 5 | } 6 | \description{ 7 | Get a Submission object, given its ID. 8 | } 9 | \usage{ 10 | synGetSubmission("123456") 11 | } 12 | \arguments{ 13 | \item{id}{ 14 | The id of the submission to retrieve. 15 | } 16 | \item{downloadFile}{ 17 | For File submissions only. If TRUE then the attached file is downloaded to the 'downloadLocation' 18 | } 19 | \item{downloadLocation}{ 20 | For File submissions only. The folder in the local file system to which the attached file is to be downloaded. 21 | If omitted, then a default location in a cache is used. See \code{\link{getFileLocation}} 22 | } 23 | \item{ifcollision}{ 24 | For File submissions only. if.collision is one of "keep.both", "keep.local", or "overwrite.local", 25 | telling the system what to do if a different file is found at the given local file location. 26 | } 27 | \item{load}{ 28 | For File submissions only. If TRUE then deserialize the downloaded file into memory, using the R 'load' command (See \code{\link{getObject}}, \code{\link{listObjects}}) 29 | } 30 | } 31 | \examples{ 32 | \dontrun{ 33 | # one of "RECEIVED","OPEN","CLOSED","SCORED","INVALID","VALIDATED","EVALUATION_IN_PROGRESS","REJECTED",or "ACCEPTED" 34 | status<-"SCORED" 35 | # get the first 100 submissions in the given evaluation queue having the given status 36 | submissions<-synGetSubmissions(evaluationId, status, limit=100, offset=0) 37 | # get the ID of an arbitrary Submission 38 | submissionId<-submissions@results[[1]]["id"] 39 | submission<-synGetSubmission(submissionId) 40 | } 41 | } 42 | \seealso{ 43 | \code{\link{synGetSubmissions}} 44 | \code{\link{synGetOwnSubmissions}} 45 | \code{\link{synGetSubmissionStatus}} 46 | } 47 | -------------------------------------------------------------------------------- /inst/unitTests/test_synPropAndAnnot.R: -------------------------------------------------------------------------------- 1 | # 2 | # Author: brucehoff 3 | ############################################################################### 4 | 5 | 6 | unitTestSetAndGetProperty <- function() { 7 | e<-Folder() 8 | checkTrue(is.null(synGetProperty(e, "id"))) 9 | synSetProperty(e, "id")<-"syn101" 10 | checkEquals("syn101", synGetProperty(e, "id")) 11 | synSetProperty(e, "id")<-NULL 12 | checkEquals(NULL, synGetProperty(e, "id")) 13 | 14 | # check that undefined property triggers error 15 | checkException(synSetProperty(e, "notAProperty")<-"foo") 16 | checkException(synGetProperty(e, "notAProperty")) 17 | 18 | e<-Folder() 19 | props<-list("id"="syn101", "name"="myFolder") 20 | synSetProperties(e)<-props 21 | checkEquals(length(props), length(intersect(props, synGetProperties(e)))) 22 | checkEquals("syn101", synGetProperty(e, "id")) 23 | checkEquals("myFolder", synGetProperty(e, "name")) 24 | } 25 | 26 | unitTestSetAndGetAnnotation <- function() { 27 | e<-Folder() 28 | synSetAnnotation(e, "myCustomAnnotation")<-"abc" 29 | checkEquals("abc", synGetAnnotation(e, "myCustomAnnotation")) 30 | 31 | expectedAnnots <- list("myCustomAnnotation"="abc") 32 | checkEquals(length(expectedAnnots), length(intersect(expectedAnnots, synGetAnnotations(e)))) 33 | 34 | synSetAnnotation(e, "myCustomAnnotation")<-NULL 35 | checkEquals(NULL, synGetAnnotation(e, "myCustomAnnotation")) 36 | checkTrue(!("myCustomAnnotation" %in% annotationNames(e))) 37 | 38 | e<-Folder() 39 | annots <-list("foo"=999, "bar"="bas") 40 | synSetAnnotations(e)<-annots 41 | checkEquals(length(annots), length(intersect(annots, synGetAnnotations(e)))) 42 | checkEquals(999, synGetAnnotation(e, "foo")) 43 | checkEquals("bas", synGetAnnotation(e, "bar")) 44 | } 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /man/synapseREST.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseGet} 2 | \alias{synapseGet} 3 | \alias{synapsePost} 4 | \alias{synapseDelete} 5 | \alias{synapsePut} 6 | \alias{.synapsePostPut} 7 | \alias{.synapseGetDelete} 8 | \title{ 9 | Synapse REST 10 | } 11 | \description{ 12 | Functions providing a low-level interface to the Synapse REST API 13 | } 14 | \usage{ 15 | synapseGet(uri, host = .getRepoEndpointLocation(), curlHandle = getCurlHandle(), anonymous = .getCache("anonymous"), path = .getRepoEndpointPrefix(), opts = .getCache("curlOpts"), entity=NULL) 16 | synapseDelete(uri, entity, host = .getRepoEndpointLocation(), curlHandle = getCurlHandle(), anonymous = FALSE, path = .getRepoEndpointPrefix(), opts = .getCache("curlOpts")) 17 | synapsePut(uri, entity, host = .getRepoEndpointLocation(), curlHandle = getCurlHandle(), anonymous = FALSE, path = .getRepoEndpointPrefix(), opts = .getCache("curlOpts")) 18 | synapsePost(uri, entity, host = .getRepoEndpointLocation(), curlHandle = getCurlHandle(), anonymous = FALSE, path = .getRepoEndpointPrefix(), opts = .getCache("curlOpts")) 19 | } 20 | %- maybe also 'usage' for other objects documented here. 21 | \arguments{ 22 | \item{uri}{ 23 | uri of the request 24 | } 25 | \item{entity}{ 26 | entity to be put or posted 27 | } 28 | \item{host}{ 29 | hostname of the server 30 | } 31 | \item{curlHandle}{ 32 | curlHandle to be used for the request 33 | } 34 | \item{anonymous}{ 35 | if TRUE, the request will be made anonymously 36 | } 37 | \item{path}{ 38 | path to the service 39 | } 40 | \item{opts}{ 41 | curl options 42 | } 43 | } 44 | 45 | \value{ 46 | an R list generated by calling fromJSON on the server response. 47 | } 48 | \author{ 49 | Matt Furia 50 | } 51 | 52 | \note{ 53 | These are internal function and should not be called by the user 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /man/synRest.Rd: -------------------------------------------------------------------------------- 1 | \name{synRestGET} 2 | \alias{synRestGET} 3 | \alias{synRestPOST} 4 | \alias{synRestPUT} 5 | \alias{synRestDELETE} 6 | \title{ 7 | Synapse REST Functions 8 | } 9 | \description{ 10 | Functions providing a generic interface to the Web Services 11 | } 12 | \usage{ 13 | synRestGET(uri, endpoint=synapseRepoServiceEndpoint()) 14 | synRestDELETE(uri, endpoint=synapseRepoServiceEndpoint()) 15 | synRestPOST(uri, body, endpoint=synapseRepoServiceEndpoint()) 16 | synRestPUT(uri, body, endpoint=synapseRepoServiceEndpoint()) 17 | } 18 | %- maybe also 'usage' for other objects documented here. 19 | \arguments{ 20 | \item{uri}{ 21 | uri of the request, e.g. "/entity/syn101", "/userProfile" 22 | } 23 | \item{body}{ 24 | body of a PUT or POST request. May be either an R list/vector or a recognized Synapse object type (i.e. a subtype of SimplePropertyOwner). 25 | } 26 | \item{endpoint}{ 27 | endpoint for the request. Default is the Synapse Respository services. See also synapseAuthServiceEndpoint(), synapseFileServiceEndpoint(). 28 | } 29 | } 30 | \details{ 31 | These functions take care of authentication, following redirects, checking if the client is black listed, checking error statuses, performing retries with exponential back off. As such the functions are not so much 'low level' as they are generic: They allow the user to access the Synapse web services using the API documents (http://rest.synapse.org) to issue requests to new services in advance of specialized convenience functions in Synapse Client. 32 | } 33 | \value{ 34 | an R list generated by calling fromJSON on the server response. 35 | } 36 | \seealso{ 37 | \code{\link{synapseRepoServiceEndpoint}} 38 | \code{\link{synapseFileServiceEndpoint}} 39 | \code{\link{synapseAuthServiceEndpoint}} 40 | \code{\link{synapsePortalEndpoint}} 41 | } 42 | 43 | 44 | -------------------------------------------------------------------------------- /R/asTableColumns.R: -------------------------------------------------------------------------------- 1 | # convenience functions for converting csv file or data frame into a list of TableColumns 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | setMethod( 7 | f = "as.tableColumns", 8 | signature = signature("data.frame"), 9 | definition = function(source, doFullFileScan=TRUE) { 10 | file<-tempfile() 11 | writeDataFrameToCSV(dataFrame=source, filePath=file) 12 | as.tableColumns(file, doFullFileScan=doFullFileScan) 13 | } 14 | ) 15 | 16 | setMethod( 17 | f = "as.tableColumns", 18 | signature = signature("character"), 19 | definition = function(source, linesToSkip=as.integer(0), quoteCharacter=character(0), 20 | escapeCharacter=character(0), separator=character(0), lineEnd=character(0), doFullFileScan=TRUE) { 21 | filePath<-source 22 | s3FileHandle<-chunkedUploadFile(filePath) 23 | request<-UploadToTablePreviewRequest( 24 | uploadFileHandleId=as.character(s3FileHandle$id), 25 | linesToSkip=linesToSkip, 26 | doFullFileScan=doFullFileScan, 27 | csvTableDescriptor=CsvTableDescriptor( 28 | quoteCharacter=quoteCharacter, 29 | isFirstLineHeader=TRUE, 30 | escapeCharacter=escapeCharacter, 31 | separator=separator, 32 | lineEnd=lineEnd) 33 | ) 34 | asyncJobId<-createS4ObjectFromList( 35 | synRestPOST("/table/upload/csv/preview/async/start", createListFromS4Object(request)), 36 | "AsyncJobId") 37 | responseBodyAsList<-trackProgress(sprintf("/table/upload/csv/preview/async/get/%s", asyncJobId@token), verbose=FALSE) 38 | responseBody<-createS4ObjectFromList(responseBodyAsList, "UploadToTablePreviewResult") 39 | list(fileHandleId=as.integer(s3FileHandle$id), tableColumns=responseBody$suggestedColumns@content) 40 | } 41 | ) 42 | 43 | 44 | -------------------------------------------------------------------------------- /R/synapseServiceEndpoint.R: -------------------------------------------------------------------------------- 1 | ## get/set the Synapse repo service endpoint 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | synapseServiceEndpoint <- 7 | function(service, endpoint) 8 | { 9 | cacheKey<-serviceEndpointCacheKey(service) 10 | if (!missing(endpoint)) { 11 | endpointObject<-parseEndpoint(endpoint) 12 | endpointObject$service<-service # i.e. along with the endpoint, we store what kind of service it's for 13 | .setCache(cacheKey, endpointObject) 14 | } else { 15 | .getCache(cacheKey) 16 | } 17 | } 18 | 19 | # TODO perhaps these public functions should be combined into one which sets all the endpoints at once 20 | synapseRepoServiceEndpoint<-function(endpoint) {synapseServiceEndpoint("REPO", endpoint)} 21 | synapseAuthServiceEndpoint<-function(endpoint) {synapseServiceEndpoint("AUTH", endpoint)} 22 | synapseFileServiceEndpoint<-function(endpoint) {synapseServiceEndpoint("FILE", endpoint)} 23 | synapsePortalEndpoint<-function(endpoint) {synapseServiceEndpoint("PORTAL", endpoint)} 24 | 25 | getEndpointForService<-function(service) {synapseServiceEndpoint(service)$endpoint} 26 | 27 | getEndpointPrefixForService<-function(service) {synapseServiceEndpoint(service)$endpointPrefix} 28 | 29 | getEndpointLocationForService<-function(service) {synapseServiceEndpoint(service)$endpointLocation} 30 | 31 | serviceEndpointCacheKey<-function(service) {sprintf("%sEndpoint", service)} 32 | 33 | parseEndpoint<-function(endpoint) { 34 | ans<-list() 35 | ans$endpoint<-endpoint 36 | url <- .ParsedUrl(url=endpoint) 37 | ans$endpointLocation <- paste(url@protocol, '://', url@authority, sep='') 38 | ans$endpointProtocol <- url@protocol 39 | ans$endpointHost <- url@authority 40 | ans$endpointPrefix <- url@path 41 | ans 42 | } 43 | 44 | -------------------------------------------------------------------------------- /man/synGet.Rd: -------------------------------------------------------------------------------- 1 | \name{synGet} 2 | \alias{synGet} 3 | \title{ 4 | Retrieve an object from Synapse 5 | } 6 | \description{ 7 | Retrieve an object from Synapse 8 | } 9 | \usage{ 10 | synGet(id, version=NULL, downloadFile=T, downloadLocation=NULL, ifcollision="keep.both", load=F) 11 | } 12 | \arguments{ 13 | \item{id}{ 14 | The Synapse ID of the entity to retrieve. 15 | } 16 | \item{version}{ 17 | Optional: The version number of the entity to retrieve. Defaults to the most recent version 18 | } 19 | \item{downloadFile}{ 20 | For File entities only. If TRUE then the attached file is downloaded to the 'downloadLocation' 21 | } 22 | \item{downloadLocation}{ 23 | For File entities only. The folder in the local file system to which the attached file is to be downloaded. 24 | If omitted, then a default location in a cache is used. See \code{\link{getFileLocation}} 25 | } 26 | \item{ifcollision}{ 27 | if.collision is one of "keep.both", "keep.local", or "overwrite.local", 28 | telling the system what to do if a different file is found at the given local file location 29 | } 30 | \item{load}{ 31 | If TRUE then deserialize the downloaded file into memory, using the R 'load' command (See \code{\link{getObject}}, \code{\link{listObjects}}) 32 | } 33 | } 34 | \details{ 35 | Get an entity (File, Folder, TableSchema, etc.) from the Synapse server, with its attributes (properties, annotations) and, 36 | optionally (for a File entity), with its associated file. 37 | } 38 | 39 | \author{ 40 | Bruce Hoff 41 | } 42 | 43 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 44 | 45 | \seealso{ 46 | \code{\link{File}} 47 | \code{\link{Folder}} 48 | \code{\link{Project}} 49 | \code{\link{TableColumn}} 50 | \code{\link{TableSchema}} 51 | \code{\link{synStore}} 52 | \code{\link{getFileLocation}} 53 | \code{\link{getObject}} 54 | \code{\link{listObjects}} 55 | } 56 | -------------------------------------------------------------------------------- /R/uploadStringToFile.R: -------------------------------------------------------------------------------- 1 | # Utility to use chunked file upload service to load a string as a single 'chunk' 2 | # Returns a file handle 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | uploadStringToSynapseS3File<-function(content, contentType="text/plain") { 7 | if (is.null(content) || nchar(content)==0) stop("Missing content.") 8 | 9 | MINIMUM_CHUNK_SIZE_BYTES<-5*1024*1024 10 | if (nchar(content)>=MINIMUM_CHUNK_SIZE_BYTES) 11 | stop("String must be less than "+MINIMUM_CHUNK_SIZE_BYTES+" bytes.") 12 | 13 | contentMD5 <- stringMd5(content) 14 | 15 | chunkedFileTokenRequest<-list( 16 | fileName="content", 17 | contentType=contentType, 18 | contentMD5=contentMD5, 19 | storageLocationId=NULL # by default this specifies the Synapse S3 storage location 20 | ) 21 | 22 | chunkedFileUploadToken<-synapsePost(uri='/createChunkedFileUploadToken', 23 | entity=chunkedFileTokenRequest, 24 | endpoint=synapseServiceEndpoint("FILE")) 25 | 26 | chunkNumber<-1 27 | ## get the signed S3 URL 28 | chunkRequest <- list(chunkNumber=chunkNumber, chunkedFileToken=chunkedFileUploadToken) 29 | chunkUploadUrl <- createChunkedFileUploadChunkURL(chunkRequest) 30 | 31 | headers <- list('Content-Type'=contentType) 32 | 33 | ## PUT the chunk to S3 34 | response <- getURLWithRetries(chunkUploadUrl, 35 | postfields = charToRaw(content), # the request body 36 | customrequest="PUT", # the request method 37 | httpheader=headers, # the headers 38 | opts=.getCache("curlOpts") 39 | ) 40 | 41 | chunkResults<-list(chunkNumber) 42 | 43 | completeChunkFileUpload(chunkedFileUploadToken, chunkResults) 44 | } 45 | 46 | #calculate the MD-5 checksum for a string 47 | stringMd5<-function(s) { 48 | digest(s, algo="md5", serialize=FALSE) 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /man/Folder.Rd: -------------------------------------------------------------------------------- 1 | \name{Folder} 2 | \alias{Folder} 3 | \title{ 4 | Synapse Folder Constructor 5 | } 6 | \description{ 7 | Constructor for Folder 8 | } 9 | \usage{ 10 | Folder(name, parentId, ...) 11 | } 12 | \arguments{ 13 | \item{name}{ 14 | Name of the Folder to be created in Synapse 15 | } 16 | \item{parentId}{ 17 | The Synapse ID of the parent Project or Folder in which to create the Folder (e.g. "syn101") 18 | } 19 | \item{...}{ 20 | Additional named parameters are interpreted as properties or annotations on the Folder 21 | } 22 | } 23 | 24 | \value{ 25 | The created Folder is returned. NOTE: This is an in-memory representation. To persist to Synapse use \code{\link{synStore}()}. 26 | } 27 | 28 | \section{Slots}{ 29 | \describe{ 30 | \item{\code{attachOwn}}{ 31 | internally used information to handle file caching 32 | } 33 | \item{\code{annotations}}{ 34 | annotations set on the object 35 | } 36 | \item{\code{synapseEntityKind}}{ 37 | in this case, 'Folder' 38 | } 39 | \item{\code{synapseWebUrl}}{ 40 | Synapse web URL 41 | } 42 | \item{\code{generatedBy}}{ 43 | the Activity which generated this Folder, if applicable (see \code{\link{Activity}}) 44 | } 45 | \item{\code{properties}}{ 46 | Synapse properties for a Folder. 47 | Properties of interest include: 48 | \describe{ 49 | \item{\code{id}}{ 50 | unique Synapse ID as set by the system upon synStore (not set by user) 51 | } 52 | \item{\code{name}}{ 53 | user supplied name 54 | } 55 | \item{\code{description}}{ 56 | user supplied description 57 | } 58 | } 59 | } 60 | } 61 | } 62 | 63 | 64 | \author{ 65 | Bruce Hoff 66 | } 67 | 68 | \seealso{ 69 | \code{\link{File}} 70 | \code{\link{Project}} 71 | \code{\link{synGet}} 72 | \code{\link{synStore}} 73 | } 74 | -------------------------------------------------------------------------------- /man/synapseLogin.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseLogin} 2 | \alias{synapseLogin} 3 | \alias{synapseLogout} 4 | \alias{invalidateAPIKey} 5 | \title{ 6 | Authentication 7 | } 8 | \description{ 9 | Functions for handling Synapse authentication. 10 | } 11 | \usage{ 12 | synapseLogin(username, password, rememberMe=F) 13 | synapseLogin(username = ..., apiKey = ..., rememberMe=F) 14 | synapseLogin(sessionToken = ..., rememberMe=F) 15 | synapseLogin(username = ..., rememberMe=F) 16 | synapseLogin() 17 | synapseLogout(localOnly=FALSE) 18 | invalidateAPIKey() 19 | } 20 | 21 | \arguments{ 22 | \item{username}{Synapse username, usually an email} 23 | \item{password}{Password associated with the username} 24 | \item{apiKey}{Can be found online by logging in and going to the Settings tab of your profile page at www.synapse.org} 25 | \item{sessionToken}{Usage not recommended} 26 | \item{rememberMe}{Boolean indicated whether login should store session information on the local machine. Defaults to FALSE} 27 | \item{localOnly}{Boolean controlling whether logout is done locally only, or propagated to Synapse} 28 | } 29 | \details{ 30 | If insufficient arguments are provided to login, either cached or configuration information may be used to supplement. 31 | The configuration file is by default located in ``~/.synapseConfig''. 32 | 33 | If logout is propagated to Synapse (ie. localOnly = FALSE), 34 | it is likely that the user will be logged out for all web clients currently in use. 35 | To logout globally across all analytical clients, use invalidateAPIKey(). 36 | } 37 | \examples{ 38 | \dontrun{ 39 | # Logging into Synapse with the rememberMe flag 40 | synapseLogin(username, password, rememberMe=TRUE) 41 | 42 | # ... Do things ... 43 | # Restart the session ... 44 | 45 | # Login with remembered credentials 46 | synapseLogin() 47 | } 48 | } 49 | \seealso{ 50 | \code{\link{Config}} 51 | } 52 | 53 | \author{Matt Furia, Joseph Wu} -------------------------------------------------------------------------------- /R/downloadEntity.R: -------------------------------------------------------------------------------- 1 | ## get an entity from Synapse and download its files 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | setMethod( 7 | f = "downloadEntity", 8 | signature = signature("character", "missing"), 9 | definition = function(entity){ 10 | downloadEntity(getEntity(entity)) 11 | } 12 | ) 13 | 14 | setMethod( 15 | f = "downloadEntity", 16 | signature = signature("character", "character"), 17 | definition = function(entity, versionId){ 18 | downloadEntity(getEntity(entity, versionId)) 19 | } 20 | ) 21 | 22 | setMethod( 23 | f = "downloadEntity", 24 | signature = signature("character", "numeric"), 25 | definition = function(entity, versionId){ 26 | downloadEntity(getEntity(entity, as.character(versionId))) 27 | } 28 | ) 29 | 30 | setMethod( 31 | f = "downloadEntity", 32 | signature = signature("numeric", "missing"), 33 | definition = function(entity){ 34 | downloadEntity(as.character(entity)) 35 | } 36 | ) 37 | 38 | setMethod( 39 | f = "downloadEntity", 40 | signature = signature("numeric", "character"), 41 | definition = function(entity, versionId){ 42 | downloadEntity(as.character(entity), versionId) 43 | } 44 | ) 45 | 46 | setMethod( 47 | f = "downloadEntity", 48 | signature = signature("numeric", "numeric"), 49 | definition = function(entity, versionId){ 50 | downloadEntity(as.character(entity), as.character(versionId)) 51 | } 52 | ) 53 | 54 | setMethod( 55 | f = "downloadEntity", 56 | signature = signature("list", "missing"), 57 | definition = function(entity){ 58 | versionId = entity$versionNumber 59 | if(is.null(versionId)){ 60 | entity <- downloadEntity(getEntity(entity)) 61 | } else { 62 | entity <- downloadEntity(getEntity(entity), as.character(versionId)) 63 | } 64 | entity 65 | } 66 | ) 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /man/annotValue_--methods.Rd: -------------------------------------------------------------------------------- 1 | \name{annotValue<--methods} 2 | \docType{methods} 3 | \alias{annotValue<--methods} 4 | \alias{annotValue<-,SynapseAnnotation,character,character-method} 5 | \alias{annotValue<-,SynapseAnnotation,character,integer-method} 6 | \alias{annotValue<-,SynapseAnnotation,character,logical-method} 7 | \alias{annotValue<-,SynapseAnnotation,character,numeric-method} 8 | \alias{annotValue<-,SynapseEntity,character,character-method} 9 | \alias{annotValue<-,SynapseEntity,character,integer-method} 10 | \alias{annotValue<-,SynapseEntity,character,logical-method} 11 | \alias{annotValue<-,SynapseEntity,character,numeric-method} 12 | \title{Methods for Function \code{annotValue<-}} 13 | \description{ 14 | Methods for function \code{annotValue<-} 15 | } 16 | \section{Methods}{ 17 | \describe{ 18 | 19 | \item{\code{signature(object = "SynapseAnnotation", which = "character", value = "character")}}{ 20 | set a character annotation 21 | } 22 | 23 | \item{\code{signature(object = "SynapseAnnotation", which = "character", value = "integer")}}{ 24 | set an integer annotation 25 | } 26 | 27 | \item{\code{signature(object = "SynapseAnnotation", which = "character", value = "logical")}}{ 28 | set a logical annotation 29 | } 30 | 31 | \item{\code{signature(object = "SynapseAnnotation", which = "character", value = "numeric")}}{ 32 | set a numeric annotation 33 | } 34 | 35 | \item{\code{signature(object = "SynapseEntity", which = "character", value = "character")}}{ 36 | set a character annotation 37 | } 38 | 39 | \item{\code{signature(object = "SynapseEntity", which = "character", value = "integer")}}{ 40 | set an integer annotation 41 | } 42 | 43 | \item{\code{signature(object = "SynapseEntity", which = "character", value = "logical")}}{ 44 | set a logical annotation 45 | } 46 | 47 | \item{\code{signature(object = "SynapseEntity", which = "character", value = "numeric")}}{ 48 | set a numeric annotation 49 | } 50 | }} 51 | \keyword{methods} 52 | -------------------------------------------------------------------------------- /inst/unitTests/test_uploadFile.R: -------------------------------------------------------------------------------- 1 | # unit tests for functions in uploadFile and uploadStringToFile 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | unitTestGetDirectorySequence <- function() { 7 | checkEquals(synapseClient:::getDirectorySequence(""), "") 8 | checkEquals(synapseClient:::getDirectorySequence("/"), "/") 9 | checkEquals(synapseClient:::getDirectorySequence("foo"), "foo") 10 | checkEquals(synapseClient:::getDirectorySequence("/foo"), "/foo") 11 | checkEquals(synapseClient:::getDirectorySequence("foo/"), "foo") 12 | checkEquals(synapseClient:::getDirectorySequence("/foo/"), "/foo") 13 | checkEquals(synapseClient:::getDirectorySequence("foo/bar"), c("foo", "foo/bar")) 14 | checkEquals(synapseClient:::getDirectorySequence("foo/bar/"), c("foo", "foo/bar")) 15 | checkEquals(synapseClient:::getDirectorySequence("/foo/bar"), c("/foo", "/foo/bar")) 16 | checkEquals(synapseClient:::getDirectorySequence("/foo/bar/"), c("/foo", "/foo/bar")) 17 | checkEquals(synapseClient:::getDirectorySequence("/foo/bar/bas"), c("/foo", "/foo/bar", "/foo/bar/bas")) 18 | checkEquals(synapseClient:::getDirectorySequence("foo/bar/bas"), c("foo", "foo/bar", "foo/bar/bas")) 19 | checkEquals(synapseClient:::getDirectorySequence("foo/bar/bas/"), c("foo", "foo/bar", "foo/bar/bas")) 20 | } 21 | 22 | unitTestCacheCredentials<-function() { 23 | testuser<-sprintf("testuser_%s", sample(1000, 1)) 24 | testpassword<-sprintf("testpassword_%s", sample(1000, 1)) 25 | synapseClient:::.setCache("sftp://testhost.com_credentials", list(username=testuser, password=testpassword)) 26 | creds<-synapseClient:::getCredentialsForHost(synapseClient:::.ParsedUrl("sftp://testhost.com/foo/bar")) 27 | checkEquals(testuser, creds$username) 28 | checkEquals(testpassword, creds$password) 29 | } 30 | 31 | unitTestStringMd5<-function() { 32 | checkEquals(synapseClient:::stringMd5("foo"), "acbd18db4cc2f85cedef654fccc4a4d8") 33 | } 34 | 35 | -------------------------------------------------------------------------------- /R/checkLatestVersion.R: -------------------------------------------------------------------------------- 1 | # Retrieves version information. 2 | # Compares own version to latest 3 | # 4 | # Author: brucehoff 5 | ############################################################################### 6 | 7 | checkLatestVersion<-function() { 8 | # get my own version 9 | myOwnVersion<-packageDescription("synapseClient", fields="Version") 10 | serverVersion<-getServerVersion() 11 | .checkLatestVersionGivenMyVersion(myOwnVersion, serverVersion) 12 | } 13 | 14 | .majorVersion<-function(v) {strsplit(v, "[-]")[[1]][1]} 15 | 16 | .majorVersionDiff<-function(v1, v2) { 17 | .majorVersion(v1) < .majorVersion(v2) 18 | } 19 | 20 | # for testing purposes returns the printed message 21 | .checkLatestVersionGivenMyVersion<-function(myOwnVersion, serverVersion) { 22 | if (is.null(myOwnVersion) || myOwnVersion=="") return("") 23 | 24 | # get the latest version, release notes, black list, and optional user message 25 | # a local cache is used to avoid making too many web service calls for this static info 26 | versionInfo <- getVersionInfo() 27 | 28 | msg <- NULL 29 | # in the unlikely/transient event that there is a more up-to-date client but that client is *blacklisted* for this server, 30 | # then we suppress telling the user to update their client. They will receive the message once the latest client works with the server 31 | if (.majorVersionDiff(myOwnVersion, versionInfo$latestVersion) && !.versionIsBlackListed(versionInfo$latestVersion, serverVersion, versionInfo$blacklist)) { 32 | msg <- sprintf("Please upgrade to the latest version of the Synapse Client, %s, by running the following commands:\n\tsource('http://depot.sagebase.org/CRAN.R')\n\tpkgInstall(\"synapseClient\")\n\n%s\n\n%s\n", 33 | versionInfo$latestVersion, versionInfo$releaseNotes, versionInfo$message) 34 | } else if (nchar(versionInfo$message)>0){ 35 | msg <- sprintf("\n\n%s\n", versionInfo$message) 36 | } 37 | if (!is.null(msg)) { 38 | message(msg) 39 | } 40 | msg 41 | } 42 | 43 | 44 | -------------------------------------------------------------------------------- /inst/integrationTests/test_fileHandleService.R: -------------------------------------------------------------------------------- 1 | 2 | # this tests the file services underlying storeEntity 3 | integrationTestFileHandle <- 4 | function() 5 | { 6 | # upload a file and receive the file handle 7 | filePath<- tempfile() 8 | connection<-file(filePath) 9 | writeChar("this is a test", connection, eos=NULL) 10 | close(connection) 11 | fileHandle<-synapseClient:::chunkedUploadFile(filePath) 12 | checkEquals(basename(filePath), fileHandle$fileName) 13 | checkEquals(synapseClient:::getMimeTypeForFile(basename(filePath)), fileHandle$contentType) 14 | # now try to retrieve the file handle given the id 15 | handleUri<-sprintf("/fileHandle/%s", fileHandle$id) 16 | fileHandle2<-synapseClient:::synapseGet(handleUri, endpoint=synapseFileServiceEndpoint()) 17 | checkEquals(fileHandle, fileHandle2) 18 | # now delete the handle 19 | synapseClient:::synapseDelete(handleUri, endpoint=synapseFileServiceEndpoint()) 20 | # now we should not be able to get the handle 21 | fileHandle3<-synapseClient:::synapseGet(handleUri, endpoint=synapseFileServiceEndpoint(), checkHttpStatus=F) 22 | checkTrue(regexpr("The resource you are attempting to access cannot be found", fileHandle3, fixed=T)[[1]]>0) 23 | } 24 | 25 | integrationTestExternalFileHandle <- function() { 26 | externalURL<-"http://google.com" 27 | contentType<-"text/html" 28 | contentSize<-1000 29 | contentMd5<-"abcdef" 30 | fileHandle <- synapseClient:::synapseLinkExternalFile(externalURL, contentType, contentSize, contentMd5, storageLocationId=NULL) 31 | checkTrue(!is.null(fileHandle$id)) 32 | checkEquals("org.sagebionetworks.repo.model.file.ExternalFileHandle", fileHandle$concreteType) 33 | checkEquals(externalURL, fileHandle$externalURL) 34 | fileName<-basename(externalURL) 35 | checkEquals(fileName, fileHandle$fileName) 36 | checkEquals(contentType, fileHandle$contentType) 37 | checkEquals(contentSize, fileHandle$contentSize) 38 | checkEquals(contentMd5, fileHandle$contentMd5) 39 | } 40 | -------------------------------------------------------------------------------- /inst/integrationTests/test_entityFileAccess.R: -------------------------------------------------------------------------------- 1 | .setUp <- 2 | function() 3 | { 4 | ## create a project to fill with entities 5 | project <- createEntity(Project()) 6 | synapseClient:::.setCache("testProject", project) 7 | } 8 | 9 | .tearDown <- 10 | function() 11 | { 12 | ## delete the test project 13 | {project<-synapseClient:::.getCache("testProject") 14 | synRestDELETE(sprintf("/entity/%s?skipTrashCan=true", propertyValue(project, "id")))} 15 | } 16 | 17 | # 18 | # This code exercises the file services underlying upload/download to/from an entity 19 | # 20 | integrationTestEntityFileAccess <- 21 | function() 22 | { 23 | # create a Project 24 | project <- synapseClient:::.getCache("testProject") 25 | checkTrue(!is.null(project)) 26 | 27 | # create a file attachment which will be used in the wiki page 28 | # upload a file and receive the file handle 29 | filePath<- tempfile() 30 | connection<-file(filePath) 31 | writeChar("this is a test", connection, eos=NULL) 32 | close(connection) 33 | 34 | fileHandle<-synapseClient:::chunkedUploadFile(filePath) 35 | 36 | # create an entity with the file 37 | entity <- list( 38 | concreteType="org.sagebionetworks.repo.model.FileEntity", # doesn't work for 'Data' 39 | name="foo", 40 | parentId=propertyValue(project, "id"), 41 | dataFileHandleId=fileHandle$id) 42 | entity <- synapseClient:::synapsePost("/entity", entity) 43 | 44 | # download the file 45 | # /entity/{enityId}/file 46 | downloadUri<-sprintf("/entity/%s/file?redirect=FALSE", entity$id) 47 | # download into a temp file 48 | downloadedFile<-synapseClient:::downloadFromService(downloadUri, destdir=synapseCacheDir())$downloadedFile 49 | origChecksum<- as.character(tools::md5sum(filePath)) 50 | downloadedChecksum <- as.character(tools::md5sum(downloadedFile)) 51 | checkEquals(origChecksum, downloadedChecksum) 52 | 53 | synRestDELETE(sprintf("/entity/%s?skipTrashCan=true", entity$id)) 54 | } -------------------------------------------------------------------------------- /R/withRetries.R: -------------------------------------------------------------------------------- 1 | # execute exponential backoff 2 | # 3 | # Author: bhoff 4 | # 5 | # fcn - the function to call, retrying on error 6 | # isRetryable - returns true iff the value returned by 'try' indicates an error which can be retried 7 | # finalizeResult - checks value returned by 'try' for errors and constructs the final result of this function 8 | # 9 | withRetries<-function(fcn, 10 | isRetryable, 11 | finalizeResult) { 12 | backoff<-initialBackOffSeconds() 13 | startTime<-Sys.time() 14 | 15 | repeat { 16 | fcnResult<-try(fcn(), silent=T) 17 | 18 | if (isRetryable(fcnResult)) { 19 | # retry 20 | if (is(fcnResult, "try-error")) { 21 | reportableResult<-fcnResult[[1]] 22 | } else { 23 | reportableResult<-fcnResult 24 | } 25 | sleepTime<-sleepTime(startTime, Sys.time(), backoff) 26 | if (sleepTime>0) { 27 | message(sprintf("Error encountered: %s. Will wait for %.1f seconds then retry. Press CTRL+C to quit.", 28 | reportableResult, sleepTime)) 29 | Sys.sleep(sleepTime) 30 | } 31 | backoff <- increaseBackoff(backoff) 32 | } else { 33 | break 34 | } 35 | if (maxWaitTimeExceeded(startTime, Sys.time())) break 36 | } # end 'repeat' loop 37 | finalizeResult(fcnResult) 38 | } 39 | 40 | initialBackOffSeconds<-function() {0.5} # half second 41 | 42 | maxWaitTimeExceeded<-function(startTime, currentTime) { 43 | maxWaitTime<-.getCache("maxWaitDiffTime") 44 | if (is.null(maxWaitTime)) stop("Missing value for maxWaitDiffTime.") 45 | currentTime-startTime>=maxWaitTime 46 | } 47 | 48 | sleepTime<-function(startTime, currentTime, backoff) { 49 | maxWaitTime<-.getCache("maxWaitDiffTime") 50 | if (is.null(maxWaitTime)) stop("Missing value for maxWaitDiffTime.") 51 | maxWaitTimeRemaining<-max(0,maxWaitTime-(currentTime-startTime)) 52 | min(backoff, maxWaitTimeRemaining) 53 | } 54 | 55 | increaseBackoff<-function(currentBackOffSeconds) { 56 | BACKOFF_MULTIPLIER <- 2 57 | MAX_BACKOFF_SECONDS<-30 58 | min(MAX_BACKOFF_SECONDS, BACKOFF_MULTIPLIER*currentBackOffSeconds) 59 | } 60 | 61 | -------------------------------------------------------------------------------- /R/curlWriter.R: -------------------------------------------------------------------------------- 1 | ## Add objects to an entity 2 | ## 3 | ## Author: Martin Morgan 4 | ############################################################################### 5 | 6 | .curlWriterOpen <- 7 | function(filename) 8 | { 9 | if (!is.character(filename) || 1L != length(filename)) 10 | stop("'filename' must be character(1)") 11 | dir <- dirname(filename) 12 | if (!file.exists(dir) || !file.info(dir)$isdir) 13 | stop("'dirname(filename)' does not exist or is not a directory") 14 | filename <- file.path(normalizePath(dir), basename(filename)) 15 | 16 | .Call("writer_open", filename) 17 | } 18 | 19 | .curlWriterClose <- 20 | function(ext) 21 | { 22 | .Call("writer_close", ext) 23 | } 24 | 25 | # Download from the given URL to the given temporary file. 26 | # Return the file name (either from the Content-Disposition header or the tail of the URL). 27 | .curlWriterDownload <- 28 | function(url, destfile, curlHandle, writeFunction=.getCache('curlWriter'), opts = .getCache("curlOpts")) 29 | { 30 | ext <- .curlWriterOpen(destfile) 31 | on.exit(.curlWriterClose(ext)) 32 | 33 | opts$noprogress <- 0L 34 | 35 | if (file.exists(destfile)) { 36 | filesize<-file.info(destfile)$size 37 | opts<-c(opts, range=sprintf("%s-", filesize)) 38 | 39 | } 40 | h = basicTextGatherer() 41 | curlPerform(URL=url, writefunction=writeFunction, headerfunction=h$update, 42 | writedata=ext, .opts = opts, curl = curlHandle) 43 | 44 | fileName<-fileNameFromHeaders(h$value()) 45 | if (is.null(fileName)) { 46 | parsedUrl<-.ParsedUrl(url) 47 | fileName<-parsedUrl@file 48 | } 49 | fileName 50 | } 51 | 52 | # looks for a header of the form: 53 | # Content-Disposition: ... filename= 54 | # If found, returns else NULL 55 | fileNameFromHeaders<-function(headers) { 56 | for (header in strsplit(headers, "\r\n", fixed=T)[[1]]) { 57 | if (1==regexpr("^Content-Disposition:", header)[1]) { 58 | pieces<-strsplit(header, "filename=")[[1]] 59 | if (length(pieces)==2) return(pieces[2]) 60 | } 61 | } 62 | NULL 63 | } 64 | -------------------------------------------------------------------------------- /R/mergeColumns.R: -------------------------------------------------------------------------------- 1 | ## Merge new columns into a data.frame 2 | ## 3 | ## Author: J. Christopher Bare 4 | ############################################################################### 5 | 6 | # Note: This might be a duplication of what's in rowMerge, so we 7 | # might want to remove one or the other. 8 | 9 | ## Given a data.frame and some potentially new field names, make sure 10 | ## that all the new fields are in the data.frame. This is done so that 11 | ## we can rbind together data.frames with potentially mismatched columns. 12 | ## 13 | ## Returns the new data.frame that results from cbinding any missing 14 | ## columns, with values set to NA. 15 | .mergeColumns <- function(df, newFieldNames) { 16 | 17 | # if df is null or empty, just return it 18 | if (is.null(df) || nrow(df)==0) 19 | return(df) 20 | 21 | # what fields are we missing? 22 | newFieldNames <- setdiff(newFieldNames, names(df)) 23 | 24 | # if df already has all needed fields, just return it 25 | if (length(newFieldNames)==0) 26 | return(df) 27 | 28 | # fill in missing fields with NAs and cbind to df 29 | newFields <- rep(list(NA),length(newFieldNames)) 30 | names(newFields) <- newFieldNames 31 | cbind(df, newFields) 32 | } 33 | 34 | ## Given two data.frames with possibly different columns, returns 35 | ## a new data.frame with all columns from both original data.frames 36 | ## and rows from the first data.frame stacked on top of rows from 37 | ## second data.frame. 38 | .mergeDataFrames <- function(df1, df2) { 39 | if (is.null(df1)) { 40 | return(df2) 41 | } 42 | 43 | if (is.null(df2)) { 44 | return(df1) 45 | } 46 | 47 | # There is no guarantee of getting the same schema in each 48 | # block, so we make sure to add any missing columns, before 49 | # we do rbind. 50 | 51 | # add new columns to first data.frame 52 | df1 <- .mergeColumns(df1, colnames(df2)) 53 | 54 | # add new columns to second data.frame 55 | df2 <- .mergeColumns(df2, colnames(df1)) 56 | 57 | # now that both data.frames have all columns, rbind them 58 | return(rbind(df1,df2)) 59 | } 60 | -------------------------------------------------------------------------------- /man/asTableColumns.Rd: -------------------------------------------------------------------------------- 1 | \name{as.tableColumns} 2 | \alias{as.tableColumns} 3 | \docType{methods} 4 | \title{ 5 | as.tableColumns 6 | } 7 | \description{ 8 | Create Table Columns based on a data frame 9 | } 10 | \usage{ 11 | as.tableColumns(source, doFullFileScan=TRUE, ... ) 12 | } 13 | \arguments{ 14 | \item{source}{ 15 | A data frame or path to a csv file 16 | } 17 | \item{doFullFileScan}{ 18 | Should the services suggest column types based on the entire file (TRUE - default) or the first 1000 rows of the file (FALSE). For large homogeneous files, doFullFileScan=FALSE will be faster, but may miss-classify the column types. 19 | } 20 | \item{linesToSkip}{ 21 | When 'source' is a file path: The number of lines to skip from the start of the file. The default value of 0 will be used if this is not provided by the caller. } 22 | \item{quoteCharacter}{ 23 | When 'source' is a file path: The character to used for quoted elements in the provided file. The default character '"' will be used if this is not provided by the caller. 24 | } 25 | \item{escapeCharacter}{ 26 | When 'source' is a file path: The escape character used for escaping a separator or quote. The default character '\\' will be used if this is not provided by the caller. 27 | } 28 | \item{lineEnd}{ 29 | When 'source' is a file path: The line feed terminator to be used for the resulting file. The default value of '\\n' will be used if this is not provided by the caller. 30 | } 31 | \item{separator}{ 32 | When 'source' is a file path: The delimiter to used for separating entries in the provided file. The default character ',' will be used if this is not provided by the caller. For tab-separated values use '\\t' 33 | } 34 | } 35 | \value{ 36 | A list containing two fields, 'tableColumns' and 'fileHandleId'. 37 | 38 | tableColumns: A list of TableColumns matching the columns in the given file or data frame in terms of name and type. 39 | 40 | fileHandleId: The ID of the uploaded file, suitable for passing to the Table constructor along with a schema. (See 'Table'.) 41 | } 42 | \seealso{ 43 | \code{\link{TableColumn},\link{Table}} 44 | } 45 | -------------------------------------------------------------------------------- /man/Table.Rd: -------------------------------------------------------------------------------- 1 | \name{Table} 2 | \alias{Table} 3 | \docType{methods} 4 | \title{ 5 | Table Constructor 6 | } 7 | \description{Constructor for a table, which can subsequently be stored in Synapse} 8 | \usage{Table(tableSchema, values)} 9 | \arguments{ 10 | \item{tableSchema}{ 11 | the schema for the table, an object of the type TableSchema or its ID 12 | } 13 | \item{values}{ 14 | the values to be stored in the table, either a data frame, the (character) file path to a CSV file, 15 | or the (integer) ID of an uploaded file (as returned by as.tableColumns). 16 | } 17 | \item{linesToSkip}{ 18 | When 'values' is a file path or ID of an uploaded file: The number of lines to skip from the start of the file. The default value of 0 will be used if this is not provided by the caller. } 19 | \item{quoteCharacter}{ 20 | When 'values' is a file path or ID of an uploaded file: The character to used for quoted elements in the provided file. The default character '"' will be used if this is not provided by the caller. 21 | } 22 | \item{isFirstLineHeader}{ 23 | When 'values' is a file path or ID of an uploaded file: Is the first line a header? The default value of 'true' will be used if this is not provided by the caller. 24 | } 25 | \item{escapeCharacter}{ 26 | When 'values' is a file path or ID of an uploaded file: The escape character used for escaping a separator or quote. The default character '\\' will be used if this is not provided by the caller. 27 | } 28 | \item{lineEnd}{ 29 | When 'values' is a file path or ID of an uploaded file: The line feed terminator to be used for the resulting file. The default value of '\\n' will be used if this is not provided by the caller. 30 | } 31 | \item{separator}{ 32 | When 'values' is a file path or ID of an uploaded file: The delimiter to used for separating entries in the provided file. The default character ',' will be used if this is not provided by the caller. For tab-separated values use '\\t' 33 | } 34 | } 35 | \seealso{ 36 | \code{\link{TableSchema},\link{RowList},\link{synStore},\link{synDownloadTableColumns}, 37 | \link{as.tableColumns},\link{synGetColumns}} 38 | } 39 | -------------------------------------------------------------------------------- /man/QueryResult.Rd: -------------------------------------------------------------------------------- 1 | \name{QueryResult} 2 | \alias{QueryResult} 3 | \alias{fetch} 4 | \alias{collect} 5 | \alias{collectAll} 6 | \title{ 7 | Retrieve Query Results 8 | } 9 | \description{ 10 | QueryResult is a reference class that enables paging through query results. 11 | } 12 | \details{ 13 | Synapse has the ability to query for entities using a SQL-like query language. 14 | See the Query service API wiki for details on how to form a query: http://sagebionetworks.jira.com/wiki/display/PLFM/Repository+Service+API#RepositoryServiceAPI-QueryAPI 15 | 16 | The QueryResult object is returned from the synapseQuery function when \code{blockSize} is specified. The 17 | client can then call either \code{fetch()} or \code{collect()} to get the next block of results as a data.frame. 18 | The difference is that with \code{collect()}, the results are accumulated. For example, after 3 calls to \code{collect()}, 19 | with a \code{blockSize} of 10 we would expect a data.frame with 30 rows. 20 | 21 | The \code{collectAll()} method repeatedly requests blocks of \code{blocksize} query results until there are no more or the 22 | limit is reached. This can be slow, so use with caution. It's usually safer to set a limit. 23 | } 24 | \author{ 25 | J. Christopher Bare 26 | } 27 | \seealso{ 28 | \code{\link{synapseQuery}} 29 | } 30 | \examples{ 31 | \dontrun{ 32 | ## get a QueryResult object back from a query 33 | qr <- synapseQuery("select id, name, parentId from file limit 1000", blockSize=100) 34 | 35 | ## get a data.frame with 100 results 36 | df <- qr$fetch() 37 | 38 | ## accumulate the next 300 results 39 | df <- qr$collect() 40 | df <- qr$collect() 41 | df <- qr$collect() 42 | 43 | # get number of rows accumulated 44 | # should be 400 with initial fetch plus 3 calls to collect 45 | length(qr) 46 | 47 | # return the selected column names 48 | names(qr) 49 | 50 | ## accumulate the remaining results. 51 | ## df will be a data.frame with all 1000 accumulated rows 52 | df <- qr$collectAll() 53 | } 54 | } 55 | \keyword{query} 56 | \keyword{results} 57 | \keyword{paging} 58 | \keyword{fetch} 59 | \keyword{collect} 60 | \keyword{collectAll} 61 | -------------------------------------------------------------------------------- /man/synapseQuery.Rd: -------------------------------------------------------------------------------- 1 | \name{synapseQuery} 2 | \alias{synapseQuery} 3 | \alias{synQuery} 4 | %- Also NEED an '\alias' for EACH other topic documented here. 5 | \title{ 6 | Query The Synapse API 7 | } 8 | \description{ 9 | Provides an interface to the Synapse API 10 | } 11 | \usage{ 12 | synapseQuery(queryStatement) 13 | synQuery(queryStatement) 14 | 15 | } 16 | %- maybe also 'usage' for other objects documented here. 17 | \arguments{ 18 | \item{queryStatement}{ 19 | The query statement 20 | } 21 | \item{blockSize}{ 22 | Defaults to NULL. If \code{blockSize} is set to an integer, returns a \code{\link{QueryResult}} object. 23 | } 24 | } 25 | \details{ 26 | See the Query service API wiki for details on how to form a query: http://sagebionetworks.jira.com/wiki/display/PLFM/Repository+Service+API#RepositoryServiceAPI-QueryAPI 27 | } 28 | \value{ 29 | Depending on whether \code{blockSize} is specified, returns a data.frame holding all query results or a \code{\link{QueryResult}} object, which enables paging through query results in increments of \code{blockSize} rows. 30 | 31 | Care should be taken to return a reasonable number of results. The service enforces a limit on the size 32 | of responses and will return an error if that limit is exceeded. Specifying only necessary columns, 33 | limiting the number of rows, and paging by specifying \code{blockSize} are all good strategies for 34 | staying within the response size limit. 35 | } 36 | 37 | \author{ 38 | Nicole Deflaux 39 | } 40 | 41 | \seealso{ 42 | \code{\link{QueryResult}} 43 | } 44 | 45 | \examples{ 46 | \dontrun{ 47 | ## query for the first 1000 Files found, returning results as a data.frame 48 | df <- synQuery("select id, name, parentId from file limit 1000") 49 | 50 | 51 | ## get a QueryResult object back from a query 52 | qr <- synQuery("select id, name, parentId from file limit 1000", blockSize=100) 53 | 54 | ## get a data.frame with 100 results 55 | df <- qr$fetch() 56 | 57 | ## accumulate the next 300 results 58 | df <- qr$collect() 59 | df <- qr$collect() 60 | df <- qr$collect() 61 | 62 | ## accumulate the remaining results. 63 | ## df will be a data.frame with 1000 accumulated rows 64 | df <- qr$collectAll() 65 | } 66 | } -------------------------------------------------------------------------------- /inst/integrationTests/test_externalFileHandle.R: -------------------------------------------------------------------------------- 1 | # integration test for external file handle 2 | # 3 | # Author: bhoff 4 | ############################################################################### 5 | 6 | .setUp <- function() { 7 | ## create a project to fill with entities 8 | project <- createEntity(Project()) 9 | synapseClient:::.setCache("testProject", project) 10 | } 11 | 12 | .tearDown <- function() { 13 | ## delete the test projects 14 | project<-synapseClient:::.getCache("testProject") 15 | synRestDELETE(sprintf("/entity/%s?skipTrashCan=true", propertyValue(project, "id"))) 16 | 17 | synapseClient:::.unmockAll() 18 | } 19 | 20 | createFile<-function(content, filePath) { 21 | if (missing(content)) content<-"this is a test" 22 | if (missing(filePath)) filePath<- tempfile() 23 | connection<-file(filePath) 24 | writeChar(content, connection, eos=NULL) 25 | close(connection) 26 | filePath 27 | } 28 | 29 | integrationTestExternalLinkLocalFile<-function() { 30 | project <- synapseClient:::.getCache("testProject") 31 | pid<-propertyValue(project, "id") 32 | 33 | # create a file to be uploaded 34 | synapseStore<-FALSE 35 | localfile<-createFile() 36 | localfile<-normalizePath(localfile, winslash="/") 37 | if (substr(localfile,1,2)=="C:") localfile=substr(localfile,3,nchar(localfile)) 38 | filePath<-paste0("file://", localfile) 39 | file<-File(filePath, synapseStore, parentId=propertyValue(project, "id")) 40 | 41 | # now store it 42 | storedFile<-synStore(file) 43 | 44 | # check that it worked 45 | checkTrue(!is.null(storedFile)) 46 | id<-propertyValue(storedFile, "id") 47 | checkTrue(!is.null(id)) 48 | checkEquals(propertyValue(project, "id"), propertyValue(storedFile, "parentId")) 49 | checkEquals(filePath, getFileLocation(storedFile)) 50 | checkEquals(synapseStore, storedFile@synapseStore) 51 | 52 | # now download it. This will pull a copy into the cache 53 | downloadedFile<-synGet(id) 54 | 55 | checkEquals(id, propertyValue(downloadedFile, "id")) 56 | checkEquals(FALSE, downloadedFile@synapseStore) 57 | 58 | fh<-downloadedFile@fileHandle 59 | checkEquals(filePath, fh$externalURL) 60 | checkEquals(file.info(localfile)$size, fh$contentSize) 61 | checkEquals(tools::md5sum(path.expand(localfile))[[1]], fh$contentMd5) 62 | } 63 | 64 | -------------------------------------------------------------------------------- /inst/unitTests/test_URL.R: -------------------------------------------------------------------------------- 1 | ## Unit test URL parser 2 | ## 3 | ## Author: Matthew D. Furia 4 | ############################################################################### 5 | 6 | .setUp <- 7 | function() 8 | { 9 | synapseClient:::.setCache("testInput","https://fakehost.com/fakePathPrefix.org/fakeFile.zip?Expires=1307658150&AWSAccessKeyId=AKIAI3BTGJG752CCJUVA&Signature=sN%2FNePyyQnkKwOWgTOxnLB5f42s%3D") 10 | } 11 | 12 | .tearDown <- 13 | function() 14 | { 15 | synapseClient:::.deleteCache("testInput") 16 | } 17 | 18 | unitTestGetProtocol <- 19 | function() 20 | { 21 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 22 | checkEquals(url@protocol, "https") 23 | } 24 | 25 | unitTestGetHost <- 26 | function() 27 | { 28 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 29 | checkEquals(url@host, "fakehost.com") 30 | } 31 | 32 | unitTestGetPathPrefix <- 33 | function() 34 | { 35 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 36 | checkEquals(url@pathPrefix, "/fakePathPrefix.org") 37 | } 38 | 39 | unitTestGetFileName <- 40 | function() 41 | { 42 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 43 | checkEquals(url@file, "fakeFile.zip") 44 | } 45 | 46 | unitTestGetQueryString <- 47 | function() 48 | { 49 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 50 | checkEquals(url@queryString, "Expires=1307658150&AWSAccessKeyId=AKIAI3BTGJG752CCJUVA&Signature=sN%2FNePyyQnkKwOWgTOxnLB5f42s%3D") 51 | } 52 | 53 | unitTestGetPath <- 54 | function() 55 | { 56 | url <- synapseClient:::.ParsedUrl(synapseClient:::.getCache("testInput")) 57 | checkEquals(url@path, "/fakePathPrefix.org/fakeFile.zip") 58 | } 59 | 60 | unitTestGetHostWithPort <- 61 | function() 62 | { 63 | url <- synapseClient:::.ParsedUrl('http://fakeHost:0000/services-authentication-fakeRelease-SNAPSHOT/auth/v1') 64 | checkEquals(url@authority, 'fakeHost:0000') 65 | checkEquals(url@host, 'fakeHost') 66 | checkEquals(url@port, '0000') 67 | checkEquals(url@path, '/services-authentication-fakeRelease-SNAPSHOT/auth/v1') 68 | checkEquals(url@file, 'v1') 69 | checkEquals(url@pathPrefix, '/services-authentication-fakeRelease-SNAPSHOT/auth') 70 | } 71 | -------------------------------------------------------------------------------- /R/SynPropertiesAndAnnotations.R: -------------------------------------------------------------------------------- 1 | # C-4 commands for getting/setting properties and annotations 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | setMethod( 8 | f = "synGetAnnotations", 9 | signature = signature("Entity"), 10 | definition = function(object) { 11 | sapply(annotationNames(object), function(x){annotValue(object,x)}, USE.NAMES=TRUE) 12 | } 13 | ) 14 | 15 | setMethod( 16 | f = "synSetAnnotations<-", 17 | signature = signature("Entity", "list"), 18 | definition = function(object, value) { 19 | for (x in annotationNames(object)) annotValue(object, x)<-NULL 20 | for (x in names(value)) annotValue(object, x)<-value[[x]] 21 | object 22 | } 23 | ) 24 | 25 | setMethod( 26 | f = "synGetProperties", 27 | signature = signature("Entity"), 28 | definition = function(object) { 29 | sapply(propertyNames(object), function(x){propertyValue(object,x)}, USE.NAMES=TRUE) 30 | } 31 | ) 32 | 33 | setMethod( 34 | f = "synSetProperties<-", 35 | signature = signature("Entity", "list"), 36 | definition = function(object, value) { 37 | for (x in propertyNames(object)) propertyValue(object, x)<-NULL 38 | for (x in names(value)) propertyValue(object, x)<-value[[x]] 39 | object 40 | } 41 | ) 42 | 43 | setMethod( 44 | f = "synGetAnnotation", 45 | signature = signature("Entity", "character"), 46 | definition = function(object, which) { 47 | annotValue(object, which) 48 | } 49 | ) 50 | 51 | setMethod( 52 | f = "synSetAnnotation<-", 53 | signature = signature("Entity", "character", "ANY"), 54 | definition = function(object, which, value) { 55 | annotValue(object, which)<-value 56 | object 57 | } 58 | ) 59 | 60 | setMethod( 61 | f = "synGetProperty", 62 | signature = signature("Entity", "character"), 63 | definition = function(object, which) { 64 | if (!(which %in% propertyNames(object))) stop(sprintf("%s is not a property in %s", which, class(object))) 65 | propertyValue(object, which) 66 | } 67 | ) 68 | 69 | setMethod( 70 | f = "synSetProperty<-", 71 | signature = signature("Entity", "character", "ANY"), 72 | definition = function(object, which, value) { 73 | propertyValue(object, which)<-value 74 | object 75 | } 76 | ) 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /R/getMimeTypeForFile.R: -------------------------------------------------------------------------------- 1 | # 2 | # getMimeTypeForFile 3 | # given a file name, determine the MIME type using the publicly available Apache mapping 4 | # 5 | 6 | # get the file's extension and then look up the MIME type, if there is no extension, apply a default 7 | getMimeTypeForFile<-function(fileName) { 8 | defaultMimeType<-"application/octet-stream" 9 | extension<-getExtension(fileName) 10 | if (nchar(extension)==0) return(defaultMimeType) # default mime type 11 | mimeTypeMap<-getMimeTypeMap() 12 | mimeType<-mimeTypeMap[[extension]] 13 | if (is.null(mimeType)) mimeType<-defaultMimeType 14 | return(mimeType) 15 | } 16 | 17 | # get the substring following the LAST "." in fname, or "" if there is no "." 18 | # this code takes into account that there may be multiple "."s in fname 19 | getExtension<-function(fname) { 20 | suffix<-fname 21 | dot<-0 22 | while (dot>=0) { 23 | lastDot<-dot 24 | suffix<-substr(suffix, dot+1, nchar(suffix)) 25 | dot<-regexpr(".", suffix, fixed=T)[[1]] 26 | if (dot==0) stop("Illegal state, dot==0") 27 | } 28 | if (lastDot==0) { 29 | return("") 30 | } else { 31 | return(tolower(suffix)) 32 | } 33 | } 34 | 35 | # use the global cache to avoid computing the (static) map more than once 36 | getMimeTypeMap<-function() { 37 | mtmCacheLabel<-"mimeTypeMap" 38 | mimeTypeMap<-.getCache(mtmCacheLabel) 39 | if (is.null(mimeTypeMap)) { 40 | mimeTypeMap<-createMimeTypeMap() 41 | .setCache(mtmCacheLabel, mimeTypeMap) 42 | } 43 | mimeTypeMap 44 | } 45 | 46 | # read the Apache MIME type list from the 'net and build a map in memory 47 | createMimeTypeMap<-function() { 48 | apacheMimeTypeURL<-"http://svn.apache.org/repos/asf/httpd/httpd/branches/2.0.x/docs/conf/mime.types"; 49 | parsedResult<-strsplit(getURLContent(apacheMimeTypeURL), "\n", fixed=TRUE)[[1]] 50 | ans<-list() 51 | for (line in parsedResult) { 52 | # skip blank lines and comments 53 | if (nchar(line)>0 && substr(line,1,1)!="#") { 54 | tokens<-strsplit(line, "[ \t]")[[1]] 55 | if (length(tokens)>1) { 56 | mimeType<-tokens[1] 57 | for (token in tokens[2:length(tokens)]) if (nchar(token)>0) ans[[token]]<-mimeType 58 | } 59 | } 60 | } 61 | # The online list does not contain a mime type for .R files 62 | ans[['r']] <- 'text/x-r' 63 | return(ans) 64 | } -------------------------------------------------------------------------------- /inst/unitTests/test_typedList.R: -------------------------------------------------------------------------------- 1 | # tests for typed lists 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | 7 | unitTestEmptyTypedList<-function() { 8 | p<-synapseClient:::UserProfile(openIds=character(0)) 9 | synapseClient:::createListFromS4Object(p) 10 | } 11 | 12 | 13 | unitTestTypedList<-function() { 14 | t<-synapseClient:::RowReferenceList() 15 | rr1<-RowReference(rowId=as.integer(1), versionNumber=as.integer(2)) 16 | rr2<-RowReference(rowId=as.integer(2), versionNumber=as.integer(2)) 17 | t[[1]]<-rr1 18 | t[[2]]<-rr2 19 | checkEquals(2, length(t)) 20 | checkEquals(t[[1]], rr1) 21 | checkEquals(t[[2]], rr2) 22 | checkEquals(list(rr1, rr2), synapseClient:::getList(t)) 23 | 24 | # test 'append' 25 | t<-synapseClient:::RowReferenceList() 26 | t[[1]]<-rr1 27 | t<-append(t, rr2) 28 | checkEquals(list(rr1, rr2), getList(t)) 29 | t<-synapseClient:::set(t, list(rr1, rr2)) 30 | checkEquals(list(rr1, rr2), getList(t)) 31 | 32 | t<-synapseClient:::RowReferenceList(rr1, rr2) 33 | checkEquals(list(rr1, rr2), getList(t)) 34 | } 35 | 36 | unitTestCreateTypedList<-function() { 37 | rr1<-RowReference(rowId=as.integer(1), versionNumber=as.integer(2)) 38 | rr2<-RowReference(rowId=as.integer(2), versionNumber=as.integer(2)) 39 | rr3<-RowReference(rowId=as.integer(3), versionNumber=as.integer(2)) 40 | created<-synapseClient:::createTypedList(c(rr1, rr2, rr3)) 41 | checkTrue(identical(synapseClient:::RowReferenceList(rr1, rr2, rr3), created)) 42 | } 43 | 44 | unitTestAppendTwoLists<-function() { 45 | r<-synapseClient:::RowReferenceList() 46 | s<-synapseClient:::RowReferenceList(synapseClient:::RowReference(rowId=as.integer(1)), synapseClient:::RowReference(rowId=as.integer(2))) 47 | t<-append(r, s) 48 | checkEquals(length(t), length(r)+length(s)) 49 | } 50 | 51 | unitTestAsTypedList<-function() { 52 | rr1<-RowReference(rowId=as.integer(1), versionNumber=as.integer(2)) 53 | rr2<-RowReference(rowId=as.integer(2), versionNumber=as.integer(2)) 54 | rr3<-RowReference(rowId=as.integer(3), versionNumber=as.integer(2)) 55 | checkEquals(synapseClient:::RowReferenceList(rr1, rr2, rr3), synapseClient:::as.RowReferenceList(list(rr1, rr2, rr3))) 56 | checkEquals(synapseClient:::RowReferenceList(rr1, rr2, rr3), synapseClient:::as.RowReferenceList(c(rr1, rr2, rr3))) 57 | } 58 | 59 | -------------------------------------------------------------------------------- /inst/integrationTests/test_asTableColumns.R: -------------------------------------------------------------------------------- 1 | # integration tests for as.TableColumns 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | integrationTest_asTableColumns<-function() { 7 | tableColumns<-as.tableColumns(system.file("resources/test/withHeaders.csv", package = "synapseClient")) 8 | checkTrue(!is.null(tableColumns$fileHandleId)) 9 | checkEquals(4, length(tableColumns$tableColumns)) 10 | checkTrue(identical(tableColumns$tableColumns[[1]], 11 | TableColumn(name="string", columnType="STRING", maximumSize=2))) 12 | checkTrue(identical(tableColumns$tableColumns[[2]], TableColumn(name="numeric", columnType="DOUBLE"))) 13 | checkTrue(identical(tableColumns$tableColumns[[3]], TableColumn(name="integer", columnType="INTEGER"))) 14 | checkTrue(identical(tableColumns$tableColumns[[4]], TableColumn(name="logical", columnType="BOOLEAN"))) 15 | 16 | # do the same thing, but starting with a data frame, rather than a file 17 | dataframe<-read.csv(system.file("resources/test/withHeaders.csv", package = "synapseClient")) 18 | tableColumns<-as.tableColumns(dataframe) 19 | 20 | checkTrue(!is.null(tableColumns$fileHandleId)) 21 | 22 | checkEquals(4, length(tableColumns$tableColumns)) 23 | checkTrue(identical(tableColumns$tableColumns[[1]], 24 | TableColumn(name="string", columnType="STRING", maximumSize=2))) 25 | checkTrue(identical(tableColumns$tableColumns[[2]], TableColumn(name="numeric", columnType="DOUBLE"))) 26 | checkTrue(identical(tableColumns$tableColumns[[3]], TableColumn(name="integer", columnType="INTEGER"))) 27 | checkTrue(identical(tableColumns$tableColumns[[4]], TableColumn(name="logical", columnType="BOOLEAN"))) 28 | 29 | ## test doFullFileScan 30 | n <- 100000 31 | tDF <- data.frame(string=sample(c("one", "two", "three"), size=n, replace=T), 32 | double=rnorm(n), 33 | stringsAsFactors=FALSE) 34 | tDF$string[n] <- "asdfasdfasdfasdfasdf" 35 | tcsTrue <- as.tableColumns(tDF) 36 | checkTrue(identical(tcsTrue$tableColumns[[1]], 37 | TableColumn(name="string", columnType="STRING", maximumSize=as.numeric(max(nchar(tDF$string)))))) 38 | tcsFalse <- as.tableColumns(tDF, doFullFileScan=FALSE) 39 | checkTrue(identical(tcsFalse$tableColumns[[1]], 40 | TableColumn(name="string", columnType="STRING", maximumSize=5))) 41 | 42 | } 43 | -------------------------------------------------------------------------------- /inst/integrationTests/test_exclusiveFileAccess.R: -------------------------------------------------------------------------------- 1 | .setUp <- 2 | function() 3 | { 4 | dir<-tempdir() 5 | filePath<-sprintf("%s/efatest.txt", dir) 6 | synapseClient:::unlockFile(filePath) 7 | } 8 | 9 | .tearDown <- 10 | function() 11 | { 12 | } 13 | 14 | integrationTestHappyPath <- 15 | function() 16 | { 17 | # lock file 18 | dir<-tempdir() 19 | filePath<-sprintf("%s/efatest.txt", dir) 20 | lockExpirationTimeStamp<-synapseClient:::lockFile(filePath, maxWaitSeconds=2, ageTimeoutSeconds=5) 21 | checkTrue(!is.na(lockExpirationTimeStamp)) 22 | # expiration is in 5 seconds, so should be less than 10 seconds from now 23 | checkTrue(lockExpirationTimeStamp=lockExpirationTimeStamp) 46 | synapseClient:::unlockFile(filePath) 47 | # check that directory is gone 48 | checkTrue(!file.exists(file.path(dirname(filePath), ".lock"))) 49 | } 50 | 51 | integrationTestAcquireLockFailure <- 52 | function() 53 | { 54 | # lock file 55 | dir<-tempdir() 56 | filePath<-sprintf("%s/efatest.txt", dir) 57 | lockExpirationTimeStamp<-synapseClient:::lockFile(filePath, maxWaitSeconds=2, ageTimeoutSeconds=5) 58 | # assume the lock is held by a process that died 59 | # second "process" fails to get the lock because it doesn't wait long enough 60 | result<-try(synapseClient:::lockFile(filePath, maxWaitSeconds=.5, ageTimeoutSeconds=5), silent=TRUE) 61 | checkTrue(class(result)=="try-error") 62 | synapseClient:::unlockFile(filePath) 63 | # check that directory is gone 64 | checkTrue(!file.exists(file.path(dirname(filePath), ".lock"))) 65 | } -------------------------------------------------------------------------------- /R/webRequestWithRetries.R: -------------------------------------------------------------------------------- 1 | # Execute a web request with retries 2 | # fcn has just one param, curlHandle 3 | # extraRetryStatusCodes is a vector of status codes to retry in addition 4 | # to the standard ones (502,503,504 see SYNR-296) 5 | # returns a list having two elements (1) the response of the web request, 6 | # (2) the returned http status code. 7 | # The result is in the form list(result, httpStatus) 8 | # 9 | # Author: brucehoff 10 | ############################################################################### 11 | 12 | webRequestWithRetries<-function(fcn, 13 | curlHandle, 14 | extraRetryStatusCodes=NULL, 15 | logErrorsToSynapse=TRUE) { 16 | 17 | isRetryable<-function(tryReturnValue) { 18 | # The error message that follow come from libcurl as enumerated here 19 | # http://curl.askapache.com/c/libcurl-errors.html 20 | # ideally we'd include an exhaustive list of transient outage conditions 21 | # from the libcurl list. Unfortunately RCurl neither exposes the numeric 22 | # value of the error condition nor generates the string in a predictable way 23 | # So we retry on everything and provide a place to list messages for which 24 | # we should not retry 25 | errorMessagesNotToRetry <- character(0) 26 | 27 | if (is(tryReturnValue, "try-error")) { 28 | # return true if there is no error message specifically tagged not to retry 29 | !any(sapply(errorMessagesNotToRetry, function(pattern){regexpr(pattern, tryReturnValue[[1]], fixed=T)[1]>=0})) 30 | } else { 31 | httpStatus<-.getCurlInfo(curlHandle)$response.code 32 | # return true if status is >=500 or 429 or in the list of statuses to retry 33 | httpStatus>=500 || httpStatus==429 || any(httpStatus==extraRetryStatusCodes) 34 | } 35 | } 36 | 37 | finalizeResult<-function(tryReturnValue) { 38 | if (is(tryReturnValue, "try-error")) { 39 | if (logErrorsToSynapse) .logErrorToSynapse("", tryReturnValue[[1]]) 40 | stop(tryReturnValue[[1]]) 41 | } else { 42 | httpStatus<-.getCurlInfo(curlHandle)$response.code 43 | # Note: We do NOT want to stop() here for non-2xx statuses. 44 | # It's the caller's business to decide how to proceed 45 | list(result=tryReturnValue, httpStatus=httpStatus) 46 | } 47 | } 48 | 49 | withRetries(fcn=function(){fcn(curlHandle)}, 50 | isRetryable=isRetryable, 51 | finalizeResult=finalizeResult) 52 | } 53 | 54 | # this is added for unit testing purposes, providing a function to override 55 | .logErrorToSynapse<-function(label, message) { 56 | logErrorToSynapse(label, message) 57 | } -------------------------------------------------------------------------------- /src/synapse_curl.c: -------------------------------------------------------------------------------- 1 | /* curl writer function for use by RCurl package 2 | * 3 | * Author: Martin Morgan 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | /* writer_open and writer_close manage the 'external pointer' that 11 | * references the C-level pointer to the opened file. _writer_finalize 12 | * is called explicitly or implicitly (when the external pointer is 13 | * garbage collected) to close the file. 14 | */ 15 | 16 | static void 17 | _writer_finalizer(SEXP ext) 18 | { 19 | if (NULL == R_ExternalPtrAddr(ext)) 20 | return; 21 | FILE *file = (FILE *) R_ExternalPtrAddr(ext); 22 | int res = fclose(file); 23 | if (0 != res) { 24 | /* FIXME: errno */ 25 | Rf_error("'writer' internal: failed to close"); 26 | } 27 | R_SetExternalPtrAddr(ext, NULL); 28 | } 29 | 30 | SEXP 31 | writer_open(SEXP filename) 32 | { 33 | FILE *file; 34 | SEXP ext; 35 | 36 | if (!isString(filename) || 1 != Rf_length(filename)) 37 | Rf_error("'filename' must be character(1)"); 38 | 39 | file = fopen(translateChar(STRING_ELT(filename, 0)), "ab"); 40 | if (NULL == file) { 41 | /* FIXME: errno */ 42 | Rf_error("'writer' failed to open file '%s'", 43 | translateChar(STRING_ELT(filename, 0))); 44 | } 45 | 46 | ext = PROTECT(R_MakeExternalPtr(file, R_NilValue, R_NilValue)); 47 | R_RegisterCFinalizerEx(ext, _writer_finalizer, TRUE); 48 | UNPROTECT(1); 49 | return ext; 50 | } 51 | 52 | 53 | SEXP 54 | writer_close(SEXP ext) 55 | { 56 | _writer_finalizer(ext); 57 | return R_NilValue; 58 | } 59 | 60 | size_t 61 | _writer_write(void *buffer, size_t size, size_t nmemb, void *data) 62 | { 63 | FILE *file = (FILE *) data; 64 | size_t len; 65 | 66 | if (NULL == file) { 67 | /* Rf_warn signals something wrong but allows the curl library 68 | * to recover. 69 | * 70 | * FIXME: wonder what happens when curl library errors? 71 | */ 72 | Rf_warning("'writer' internal: NULL FILE pointer"); 73 | return 0; /* trigger error in curl? */ 74 | } 75 | 76 | len = fwrite(buffer, size, nmemb, file); 77 | if (len != nmemb) 78 | /* Rf_warning here; error in curl library. 79 | * 80 | * FIXME: wonder what happens when curl library errors? 81 | */ 82 | Rf_warning("'writer' internal: bytes written != bytes in buffer"); 83 | 84 | return len; 85 | } -------------------------------------------------------------------------------- /R/createListFromS4Object.R: -------------------------------------------------------------------------------- 1 | # create a list version of an S4 object, suitable for serialization to JSON. 2 | # 3 | # Author: brucehoff 4 | ############################################################################### 5 | 6 | createListFromS4Object<-function(obj) { 7 | if (is.null(obj) || is(obj, "NullS4Object")) return(NULL) 8 | schemaDef <- readEntityDef(getSchemaNameFromS4ClassName(class(obj)), getSchemaPath()) 9 | createListFromS4ObjectIntern(obj, schemaDef) 10 | } 11 | 12 | getSchemaForProperty<-function(property) { 13 | schemaType<-schemaTypeFromProperty(property) 14 | isPrimitive<-length(TYPEMAP_FOR_ALL_PRIMITIVES[[schemaType]])>0 15 | if (isPrimitive || schemaType=="array") { 16 | property 17 | } else { 18 | readEntityDef(schemaType, getSchemaPath()) 19 | } 20 | } 21 | 22 | 23 | createListFromS4ObjectIntern<-function(obj, schemaDef) { 24 | if (is.null(obj) || is(obj, "NullS4Object")) return(NULL) 25 | 26 | if (isPrimitiveType(class(obj))) { 27 | if (length(obj)==0) return(NULL) 28 | if (schemaTypeFromProperty(schemaDef)=="array") { 29 | return(as.list(obj)) 30 | } else { 31 | return(obj) 32 | } 33 | } 34 | result <-list() 35 | if (is(obj, "TypedList")) { 36 | elemSchema<-getSchemaForProperty(getArraySubSchema(schemaDef)) 37 | if (length(obj)>0) { 38 | for (i in 1:length(obj)) { 39 | result[[1+length(result)]]<-createListFromS4ObjectIntern(obj[[i]], elemSchema) 40 | } 41 | } 42 | return(result) 43 | } 44 | 45 | # at this point we know obj is an S4 class 46 | effectiveSchemaProperties<-getEffectivePropertySchemas(getSchemaNameFromS4ClassName(class(obj)), getSchemaPath()) 47 | for (slotName in slotNames(obj)) { 48 | if (slotName=="autoGeneratedExtra") next 49 | property<-effectiveSchemaProperties[[slotName]] 50 | elemSchema<-getSchemaForProperty(property) 51 | value<-slot(obj, slotName) 52 | result[[slotName]]<-createListFromS4ObjectIntern(value, elemSchema) 53 | } 54 | for (name in names(obj@autoGeneratedExtra)) { 55 | if (any(name==names(result))) 56 | stop(sprintf("'extra' field %s collides with existing element in object of type %s", name, class(obj))) 57 | result[[name]]<-obj@autoGeneratedExtra[[name]] 58 | } 59 | 60 | # An object with no field values becomes an empty list. 61 | # To keep RJSONIO from erroneously encoding as an empty _JSON_ list ("[]") 62 | # we replace it with NULL 63 | if (length(result)==0) { 64 | NULL 65 | } else { 66 | result 67 | } 68 | } 69 | --------------------------------------------------------------------------------